Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading