[英]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.