0

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

Slevin
  • 617
  • 1
  • 7
  • 17

1 Answers1

0

The code mostly looked correct. Minor tweaks got it working.

        public static Map<String, Map<String, Integer>> locations(List<LocationPair> locationPairs) {
            return locationPairs.stream()
                    .collect(
                            Collectors.groupingBy(LocationPair::getPosition, Collectors.toMap(LocationPair::getDestination, LocationPair::getDistance)));
        }

Using variables instead of method references, this becomes -

locationPairs.stream()
                    .collect(
                            Collectors.groupingBy(tmp -> tmp.position, Collectors.toMap(tmp2 -> tmp2.destination, tmp2 -> tmp2.distance)));

Hope this helps. Let me know in-case I missed something

Sahil Agarwal
  • 142
  • 1
  • 8
  • Would it maybe possible to you to provide a code snippet for the second sample where the grouping data is already passed as map? – Slevin Mar 10 '21 at 18:49
  • @Slevin the second code isn't clear. Could you please edit the question to explain it better? – Sahil Agarwal Mar 10 '21 at 19:24
  • 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. That would mean, that this code >> Collectors.toMap(pair.target, pair.distance) << should be replaced with an already existin map. – Slevin Mar 10 '21 at 19:32