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 wanted 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.
Map<Object, Object> result1 = keys.stream()
.map(key -> List.of(key, values.stream().filter(value -> value.contains(key)).toList()))
.collect(Collectors.toMap(data -> data.get(0), data -> data.get(1)));
This worked but seems ugly.
I thought there should be an efficient way more than this one.
Show me the best way to improve this.