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.
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.
CodePudding user response:
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()
));