简体   繁体   English

Java8 Stream:分组并创建 Map

[英]Java8 Stream: groupingBy and create Map

I want to get the following Data structure: Map<String, Map<String, Integer>>我想得到以下数据结构: 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).给定一个 class 或者包含字段 als 基元(位置、目的地、距离)或作为键(位置)加上 map(目标)。 From each unique position one can target to many destinations (by distance).从每个独特的 position 可以定位到许多目的地(按距离)。

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.关于第二个代码片段:结果应该与第一个代码相同。唯一的区别是,LocationPair 中提供的数据已经过进一步处理,因此目的地和距离已经放入其目标地图中。

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非常感谢您的帮助

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让我知道以防我错过了什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM