简体   繁体   中英

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)?

My goal is to order both maps by its keys (BigDecimal and Optional BigDecimal) but im not sure how to do this with lambda...

If you're using the mapSupplier you can use a SortedMap like 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:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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