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

Create Map from two lists with some filtering

I got two Lists as follows

List<String> keys = List.of("A1", "B1", "A2", "B2");
List<List<String>> values = List.of(List.of("A1", "B1"), List.of("A2", "B2"), List.of("A1", "B2"), List.of("A2", "B1"));

And I want to make a Map from those two Lists at the declaration time.

Map<String, List<List<String>>> result = Map.ofEntries(
    Map.entry("A1", List.of(List.of("A1", "B1"), List.of("A1", "B2"))),
    Map.entry("A2", List.of(List.of("A2", "B2"), List.of("A2", "B1"))),
    Map.entry("B1", List.of(List.of("A1", "B1"), List.of("A2", "B1"))),
    Map.entry("B2", List.of(List.of("A2", "B2"), List.of("A1", "B2")))
)

As you can see, each map entry‘s value gathers values entry containing the key’s value.

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

I tried to make this Map object using stream api, map method and filter method.

But I couldn’t make it.

Show me the best way to make this one.

>Solution :

First stream the keys, and use the toMap collector. You specify what the keys and values of the map are, in terms of an element in the keys list.

The keys of the map are just the elements of the keys list, unchanged, and that the values of the map are the (inner) lists of values that contains the element in the keys list. This is where you can stream the values list and filter.

var result = keys.stream().collect(Collectors.toMap(
    key -> key, // or Function.identity()
    key -> values.stream().filter(value -> value.contains(key)).toList()
));
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