How to map list from another list Stream Api

I have a task and I am familiar with Java 8 but actually do not reckon how to do this one: so we have 2 lists , one is Integer, second – String.

  • for each value n from integerList select a string from stringList that starts with a digit and has length n;
  • if there are several required strings in the stringList, select the first one;
  • if there are no required string, place Not found as an appropriate element.

What I have tried to implement:

public static List<String> f(List<Integer> integerList, List<String> stringList) {
            integer ->
                    .findFirst().orElse("Not found")

Not sure that know what to write in filter


integerList = [1, 3, 4]
stringList = ["1aa", "aaa", "1", "a"]


["1", "1aa", "Not Found"]

Do you have any ideas how to implement it?

>Solution :

You can generate from the list of strings a map Map<Integer,String>, which associates string length with the first string in a list having this length.

And then process the contents of the list of integers.

List<Integer> integerList = List.of(1, 3, 4);
List<String> stringList = List.of("1aa", "aaa", "1", "a");
Map<Integer, String> strByLength =
        String::length,       // key
        Function.identity(),  // value
        (left, right) -> left // pick the first value
List<String> result1 =
    .map(i -> strByLength.getOrDefault(i, "Not Found"))


[1, 1aa, Not Found]

It can also be done by creating a nested stream inside map() operation, i.e. in the way that tried. For that you need the following predicate in the filter():

.filter(str -> str.length() == integer)

Leave a Reply