Removing duplicates and sorting collected elements into value of a Map

Adam Jungen :

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?

Deadpool :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143921&siteId=1