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

Elements in second list matched with elements in first list

I have 2 lists as the following

List<String> firstList = Arrays.asList("E","B","A","C");
List<String> secondList = Arrays.asList("Alex","Bob","Chris","Antony","Ram","Shyam");

I want the output in the form of a map having values in the second list mapped to elements in the first list based on first character.

For example I want the output as

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

Map<String,List<String>> outputMap;

and it has the following content

key -> B, value -> a list having single element Bob
key -> A, value -> a list having elements Alex and Antony
key -> C, value -> a list having single element Chris

I did something like this

    firstList.stream()
    .map(first-> 
              secondList.stream().filter(second-> second.startsWith(first))
             .collect(Collectors.toList())
    );

and can see the elements of the second list group by first character. However I am unsure as to how to store the same in a map .
Please note that my question is more from the perspective of using the streaming API to get the job done.

>Solution :

I’m pretty sure that instead of nesting streaming of both lists you should just group the second one by first letter and filter values by testing whether the first letter is in the first list

final Map<String, List<String>> result = secondList.stream()
    .filter(s -> firstList.contains(s.substring(0, 1)))
    .collect(Collectors.groupingBy(s -> s.substring(0, 1)));

You can also extract s.substring(0, 1) to some

String firstLetter(String string)

method to make code a little bit more readable

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