Lambda Collectors.groupingBy将结果映射到嵌套映射

Lambda Collectors.groupingBy将结果映射到嵌套映射,lambda,java-8,grouping,Lambda,Java 8,Grouping,我有以下代码 Map<Long,String> timeMap= new HashMap<>(); Map<Boolean, List<Map.Entry<Long,String>>> output= timeMap.entrySet().parallelStream() .filter(map -> map.getKey()-Instant.now().toEpochMilli()>120

我有以下代码

 Map<Long,String> timeMap= new HashMap<>();
    Map<Boolean, List<Map.Entry<Long,String>>> output= timeMap.entrySet().parallelStream()
            .filter(map -> map.getKey()-Instant.now().toEpochMilli()>120000)
            .collect(Collectors.groupingBy(o -> o.getKey()<600000));

嵌套的
收集器是一种更好的方法:

Map<Boolean, Map<Long, String>> collect = timeMap.entrySet().stream()
    .filter(e -> e.getKey() - Instant.now().toEpochMilli() > 120_000)
    .collect(
        Collectors.partitioningBy(e -> e.getKey() < 600_000, 
            Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)
        ));
Map collect=timeMap.entrySet().stream()
.filter(e->e.getKey()-Instant.now().toEpochMilli()>120_000)
.收集(
收集器。分区方式(e->e.getKey()<600_000,
toMap(Map.Entry::getKey,Map.Entry::getValue)
));

这里有一种没有流的方法:

Map<Boolean, Map<Long, String>> booleanMapMap = new HashMap<>();
timeMap.forEach((k, v) -> {
    if (k - Instant.now().toEpochMilli() > 120_000)
        booleanMapMap.computeIfAbsent(k < 600_000, dummy -> new HashMap<>()).put(k, v);
});
Map booleanmapp=newhashmap();
forEach(k,v)->{
如果(k-Instant.now().toEpochMilli()>120_000)
booleanmap.computeIfAbsent(k<600_000,dummy->newhashmap()).put(k,v);
});
为了避免NPE,您应该按如下方式从外部地图检索:

Map<Long, String> trueMap = booleanMapMap.getOrDefault(true, new HashMap<>());
Map trueMap=booleanmapp.getOrDefault(true,new HashMap());

如果您想保持条目的插入顺序,只需更改
dummy->new HashMap()
,方法是
dummy->new LinkedHashMap()

重复这一点,我正要开始回答,这时弹出了这个答案。PartitionBy是这里的关键,不仅因为它有效,而且考虑到手头的问题,在语义上也是如此。
Map<Boolean, Map<Long, String>> booleanMapMap = new HashMap<>();
timeMap.forEach((k, v) -> {
    if (k - Instant.now().toEpochMilli() > 120_000)
        booleanMapMap.computeIfAbsent(k < 600_000, dummy -> new HashMap<>()).put(k, v);
});
Map<Long, String> trueMap = booleanMapMap.getOrDefault(true, new HashMap<>());