I want to get the following Data structure: Map<String, Map<String, Integer>>
Given is a class either containing the fields als primitives (position, destination, distance) or as a key (position) plus map (target). From each unique position one can target to many destinations (by distance).
private static class LocationPair {
String position, destination;
int distance;
}
Map<String, Map<String, Integer>> locations = locationPairs.stream()
.collect(Collectors.groupingBy(pair -> pair.position, Collectors.toMap(pair.destination, pair.distance)));
private static class LocationPair {
String position;
Map<String, Integer> target = Collections.singletonMap(destination, distance);
}
Map<String, Map<String, Integer>> locations = locationPairs.stream()
.collect(Collectors.groupingBy(pair -> pair.position, Collectors.mapping(pair -> pair.target)));
Regarding the second code-snippet: The result should be the same as in the first code.The only difference is, that the provided data in LocationPair have been further processed so that destination and distance have been put already into their target-Map.
I know this must be possible, but somehow I can't figure it out how to get it done. The stream-code snippets above shall show what I mean although I know that they aren't working.
Many thanks for any help