【问题标题】:Collectors groupingBy insertion, ascending and descending order - java8收集器分组按插入,升序和降序 - java8
【发布时间】:2019-11-06 21:32:34
【问题描述】:

样本数据

List<Test> tests = new ArrayList();

Test test3 = new Test();
test3.setName("FELLOW");
test3.setDescription("DESC FELLOW 1");
tests.add(test3);

Test test4 = new Test();
test4.setName("FELLOW");
test4.setDescription("DESC FELLOW 2");
tests.add(test4);

Test test = new Test();
test.setName("HELLO");
test.setDescription("DESC Hello 1");
tests.add(test);

Test test1 = new Test();
test1.setName("HELLO");
test1.setDescription("DESC Hello 2");
tests.add(test1);

Test test2 = new Test();
test2.setName("HELLO");
test2.setDescription("DESC Hello 3");
tests.add(test2);

Test test5 = new Test();
test5.setName("ABC");
test5.setDescription("DESC FELLOW 3");
tests.add(test5);

Test test6 = new Test();
test6.setName("ABC");
test6.setDescription("DESC ABC 1");
tests.add(test6);

为了按插入顺序获取数据,我使用了 LinkedHashMap

Map<String, List<Test>> insertionOrder = tests.stream().collect(Collectors.groupingBy(Test::getName, LinkedHashMap::new, Collectors.toList()));

结果:

FELLOW,
HELLO
ABC

为了按升序获取数据,我使用了TreeMap

Map<String, List<Test>> ascendingOrder = tests.stream().collect(Collectors.groupingBy(Test::getName, TreeMap::new, Collectors.toList()));

结果:

ABC,
FELLOW
HELLO

如何按降序获取地图?例如?

HELLO,
FELLOW
ABC

【问题讨论】:

  • TreeMap(Comparator&lt;? super K&gt; comparator)

标签: java sorting java-8 collectors


【解决方案1】:

Comparator 传递给TreeMap 构造函数。例如:

Map<String, List<Test>> descendingOrder = 
    tests.stream()
         .collect(Collectors.groupingBy(Test::getName,
                                        () -> new TreeMap(Comparator.naturalOrder().reversed()),
                                        Collectors.toList()));

或者:

Map<String, List<Test>> descendingOrder = 
    tests.stream()
         .collect(Collectors.groupingBy(Test::getName,
                                        () -> new TreeMap<>(Collections.reverseOrder()),
                                        Collectors.toList()));

【讨论】:

  • 感谢给了想法Map&lt;String, List&lt;Test&gt;&gt; descendingOrder1 = tests.stream().collect(Collectors.groupingBy(Test::getName, () -&gt; new TreeMap&lt;&gt;(Collections.reverseOrder()), Collectors.toList()));工作!
  • 为什么不只是Comparator.reverseOrder(),比如Map&lt;String, List&lt;Test&gt;&gt; ascendingOrder = tests.stream() .collect(groupingBy(Test::getName, () -&gt; new TreeMap&lt;&gt;(Comparator.reverseOrder()), Collectors.toList()));
  • @davidxxx 有时我想到的第一个解决方案并不是最简单的解决方案。您的解决方案也有效。
  • 我们在修改旧代码时会偶然发现Collections.reverseOrder(Collections.reverseOrder()),因为Comparator.naturalOrder() 在Java 8 之前并不存在……
猜你喜欢
  • 1970-01-01
  • 2012-11-08
  • 2023-03-07
  • 2018-03-18
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 2015-08-30
  • 2011-08-25
相关资源
最近更新 更多