简体   繁体   中英

Collectors groupingBy insertion, ascending and descending order - java8

Sample Data

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

To get data in insertion order, I used LinkedHashMap

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

result:

FELLOW,
HELLO
ABC

To get data in ascending order, I used TreeMap

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

result:

ABC,
FELLOW
HELLO

How to get Map in descending order ? for example ?

HELLO,
FELLOW
ABC

Pass a Comparator to the TreeMap constructor. For example:

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

Or:

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

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