简体   繁体   中英

Removing duplicates and sorting collected elements into value of a Map

This is Person class

public class Person {

    private String department;
    private long timestamp;

    //getters and setters
}

I'm trying to do collect them into Map using groupingBy

Map<String, List<Long>> map = 
        personList.stream()
              .collect(groupingBy(
                         Person::getDepartment,
                         mapping(Person::getTimestamp, toList())
                        )
                  );

This map has values of List<Long> and I wanted to remove duplicates and sort these lists. Therefore I used collectingAndThen, but it didn't work and gives error.

Map<String, List<Long>> map = 
        personList.stream()
              .collect(groupingBy(
                         Person::getDepartment,
                         mapping(Person::getTimestamp, collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparingLong(Person::getTimestamp))),
                                ArrayList::new))));

What is wrong here?

You are collecting into Map<String, List<Long>> were list is of Long type, so you cannot sort the list using Person::getTimestamp . Since you are using TreeSet by default it will sort according to the natural ordering of its elements.

Map<String, List<Long>> map1 = personList.stream()
            .collect(Collectors.groupingBy(Person::getDepartment,
                    Collectors.mapping(Person::getTimestamp,
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(TreeSet::new),
                                    ArrayList::new))));

Either converting TreeSet because it removes duplicates and by default sort according to the natural ordering of its elements.

Map<String, Set<Long>> map = personList.stream()
            .collect(Collectors.groupingBy(Person::getDepartment, Collectors.mapping(Person::getTimestamp,
                    Collectors.toCollection(TreeSet::new)));

Have you tried something like below

for (String key : map.keySet()) {
     List<Long> list = map.get(key);
     List<Long> listWithoutDuplicates = list.stream().distinct().collect(Collectors.toList());
     map.put(key, listWithoutDuplicates)
}

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