简体   繁体   中英

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

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.

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

Just move that filter to a toMap() collector:

Map<String, List<String>> grouped = firstList.stream()
        .collect(Collectors.toMap(first -> first, first -> secondList.stream()
                .filter(second -> second.startsWith(first))
                .collect(Collectors.toList())));

If you want only keys that have matching names, you can

.filter(first -> secondList.stream().anyMatch(second -> second.startsWith(first)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM