收藏家分组按插入,升序和降序-Java8

时间:2019-06-25 05:30:41

标签: java sorting java-8 collectors

样本数据

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

如何按降序获取Map?例如?

HELLO,
FELLOW
ABC

1 个答案:

答案 0 :(得分:2)

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