Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream API toMap converting to TreeMap

public class Message {
    private int id;
    private User sender;
    private User receiver;
    private String text;   
    private Date senddate;
..
}

I have

List<Message> list= new ArrayList<>();

I need to transform them to

TreeMap<User,List<Message>> map

I know how to do transform to HashMap using

list.stream().collect(Collectors.groupingBy(Message::getSender));

But I need TreeMap with: Key - User with newest message senddate first Value - List sorted by senddate newest first

Part of User class

    public class User{
    ...
    private List<Message> sendMessages;
    ...

   public List<Message> getSendMessages() {
        return sendMessages;
    }

}

User comparator:

     public class Usercomparator implements Comparator<User> {
        @Override
        public int compare(User o1, User o2) {
            return o2.getSendMessages().stream()
.map(message -> message.getSenddate())
.max(Date::compareTo).get()
           .compareTo(o1.getSendMessages().stream()
.map(message1 -> message1.getSenddate())
.max(Date::compareTo).get());
        }
    }
like image 391
VoldemarP Avatar asked Jan 31 '16 16:01

VoldemarP


People also ask

Can we convert HashMap to TreeMap in Java?

Get the HashMap to be converted. Create a new TreeMap. Pass the hashMap to putAll() method of treeMap. Return the formed TreeMap.

How will you convert a list into map using streams in Java 8?

With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.

How do you collect from TreeMap?

Collect the data directly to a TreeMap by using the overloaded toMap(keyMapper, valueMapper, mergeFunction, mapSupplier) method that allows you to specify which Map to create (4th parameter). Is there a function that omits the merger function but specifies the map supplier? @francescofoschi No.


1 Answers

You can use overloaded groupingBy method and pass TreeMap as Supplier:

TreeMap<User, List<Message>> map = list
            .stream()
            .collect(Collectors.groupingBy(Message::getSender,
                    () -> new TreeMap<>(new Usercomparator()), toList()));
like image 199
Mrinal Avatar answered Sep 21 '22 15:09

Mrinal