[英]Java 8 / Lambda: multiple collect/Collectors.groupingBy with sorting
我有以下代码
Map<BigDecimal, Map<Optional<BigDecimal>, List<TestDto>>> test = data.getTestDtos().stream()
.collect(
Collectors.groupingBy(TestDto::getValue1,
Collectors.groupingBy(dto -> Optional.ofNullable(dto.getValue2()))));
是否有机会至少按其键(BigDecimal)对外部/第一张地图进行排序?
我的目标是通过键(BigDecimal和Optional BigDecimal)对两个地图进行排序,但是我不确定如何使用lambda来完成此操作...
如果您使用的是mapSupplier
,则可以使用SortedMap
类的TreeMap
。
SortedMap<BigDecimal, Map<Optional<BigDecimal>, List<TestDto>>> test = data.getTestDtos()
.stream()
.collect(
Collectors.groupingBy(TestDto::getValue1, TreeMap::new,
Collectors.groupingBy(dto -> Optional.ofNullable(dto.getValue2()))));
要对内部Map
排序,您必须编写自己的Optional-Comparator
,解决方案应如下所示:
SortedMap<BigDecimal, SortedMap<Optional<BigDecimal>, List<TestDto>>> test = data
.getTestDtos()
.stream()
.collect(
Collectors.groupingBy(TestDto::getValue1, TreeMap::new,
Collectors.groupingBy(dto -> Optional.ofNullable(dto.getValue2()),
() -> new TreeMap<>((o1, o2) -> {
if (o1.isPresent() && o2.isPresent()) {
return o1.get().compareTo(o2.get());
} else if (o1.isPresent()) {
return -1;
} else if (o2.isPresent()) {
return 1;
} else {
return 0;
}
}),
Collectors.toList())
)
);
您只需要从HashMap
创建一个TreeMap
,它将被排序
Map<String, String> treeMap = new TreeMap<>(test);
丑解是
Map<BigDecimal, Map<Optional<BigDecimal>, List<String>>> sorted = test.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getKey))
.peek(entry -> entry.setValue(new TreeMap<>(entry.getValue())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.