简体   繁体   English

Java 8 / Lambda:多个collect / Collectors.grouping通过排序

[英]Java 8 / Lambda: multiple collect/Collectors.groupingBy with sorting

Im having the following code 我有以下代码

    Map<BigDecimal, Map<Optional<BigDecimal>, List<TestDto>>> test =  data.getTestDtos().stream()
    .collect(
            Collectors.groupingBy(TestDto::getValue1,
            Collectors.groupingBy(dto -> Optional.ofNullable(dto.getValue2()))));

Is there any chance to sort at least the outer/first map by its keys (BigDecimal)? 是否有机会至少按其键(BigDecimal)对外部/第一张地图进行排序?

My goal is to order both maps by its keys (BigDecimal and Optional BigDecimal) but im not sure how to do this with lambda... 我的目标是通过键(BigDecimal和Optional BigDecimal)对两个地图进行排序,但是我不确定如何使用lambda来完成此操作...

If you're using the mapSupplier you can use a SortedMap like TreeMap . 如果您使用的是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()))));

To sort the inner Map you have to write your own Optional-Comparator and the solution should look like this: 要对内部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);

Ugly solution is 丑解是

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.

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