Java 8 : How to sort a collection with Streams?

For do this you can use :

.stream().sorted(new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getId().compareTo(o2.getId());
    }
})

Look a real example where I ‘m using sorted plus groupingBy.

myMap = myList.getQuestions()
     .stream().sorted(new Comparator<MyObject>() {
         @Override
         public int compare(MyObject o1, MyObject o2) {
           return o1.getId().compareTo(o2.getId());
         }
     })
     .collect(groupingBy(Question::Category));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s