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.
task:

  • 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) {
    return integerList.stream().map(
            integer -> stringList.stream()
                    .filter()
                    .findFirst().orElse("Not found")
    ).collect(Collectors.toList());
}

Not sure that know what to write in filter

Input:

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

Output:

["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 = stringList.stream()
    .collect(Collectors.toMap(
        String::length,       // key
        Function.identity(),  // value
        (left, right) -> left // pick the first value
    ));
    
List<String> result1 = integerList.stream()
    .map(i -> strByLength.getOrDefault(i, "Not Found"))
    .toList();
    
System.out.println(result1);

Output:

[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