Java 8/Lambda:multiple collect/collector.groupingBy with sorting
我有以下代码Java 8/Lambda:multiple collect/collector.groupingBy with sorting,java,java-8,Java,Java 8,我有以下代码 Map<BigDecimal, Map<Optional<BigDecimal>, List<TestDto>>> test = data.getTestDtos().stream() .collect( Collectors.groupingBy(TestDto::getValue1, Collectors.groupingBy(dto -> Optional.
Map<BigDecimal, Map<Optional<BigDecimal>, List<TestDto>>> test = data.getTestDtos().stream()
.collect(
Collectors.groupingBy(TestDto::getValue1,
Collectors.groupingBy(dto -> Optional.ofNullable(dto.getValue2()))));
Map test=data.getTestDtos().stream()
.收集(
Collectors.groupingBy(TestDto::getValue1,
Collectors.groupby(dto->Optional.ofNullable(dto.getValue2());
是否有机会至少按键(BigDecimal)对外部/第一个映射进行排序
我的目标是按键(BigDecimal和可选的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()))));
您只需从
HashMap
创建一个TreeMap
,它就会被排序
Map<String, String> treeMap = new TreeMap<>(test);
Map treeMap=新的treeMap(测试);
丑陋的解决方案是
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));
Map sorted=test.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getKey))
.peek(entry->entry.setValue(新树映射(entry.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
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));