Main Tutorials

Java 8 – How to sort list with stream.sorted()

Few examples to show you how to sort a List with stream.sorted()

1. List

1.1 Sort a List with Comparator.naturalOrder()


package com.mkyong.sorted;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamApplication {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("9", "A", "Z", "1", "B", "Y", "4", "a", "c");

        /* 
		List<String> sortedList = list.stream()
			.sorted(Comparator.naturalOrder())
			.collect(Collectors.toList());
			
        List<String> sortedList = list.stream()
			.sorted((o1,o2)-> o1.compareTo(o2))
			.collect(Collectors.toList());
		*/

		List<String> sortedList = list.stream().sorted().collect(Collectors.toList());
		
        sortedList.forEach(System.out::println);

    }
}

Output


1
4
9
A
B
Y
Z
a
c

1.2 Sort a List with Comparator.reverseOrder()


package com.mkyong.sorted;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class StreamApplication {

    public static void main(String[] args) {

        List<String> list = Arrays.asList("9", "A", "Z", "1", "B", "Y", "4", "a", "c");

        /*
		List<String> sortedList = list.stream()
			.sorted((o1,o2)-> o2.compareTo(o1))
			.collect(Collectors.toList());
		*/
		
        List<String> sortedList = list.stream()
			.sorted(Comparator.reverseOrder())
			.collect(Collectors.toList());

        sortedList.forEach(System.out::println);

    }
}

Output


c
a
Z
Y
B
A
9
4
1

2. List Objects

1.1 Sort by age, natural order.


package com.mkyong.sorted;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class StreamApplication {

    static List<User> users = Arrays.asList(
            new User("C", 30),
            new User("D", 40),
            new User("A", 10),
            new User("B", 20),
            new User("E", 50));

    public static void main(String[] args) {
        
        /*List<User> sortedList = users.stream()
			.sorted((o1, o2) -> o1.getAge() - o2.getAge())
			.collect(Collectors.toList());*/
			
        List<User> sortedList = users.stream()
			.sorted(Comparator.comparingInt(User::getAge))
			.collect(Collectors.toList());
 
        sortedList.forEach(System.out::println);

    }

    static class User {

        private String name;
        private int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}

Output


User{name='A', age=10}
User{name='B', age=20}
User{name='C', age=30}
User{name='D', age=40}
User{name='E', age=50}

1.2 reverse order.


	List<User> sortedList = users.stream()
		.sorted(Comparator.comparingInt(User::getAge)
		.reversed())
		.collect(Collectors.toList());

    sortedList.forEach(System.out::println);

Output


User{name='E', age=50}
User{name='D', age=40}
User{name='C', age=30}
User{name='B', age=20}
User{name='A', age=10}

1.3 Sort by name


	/*List<User> sortedList = users.stream()
		.sorted((o1, o2) -> o1.getName().compareTo(o2.getName()))
		.collect(Collectors.toList());*/
    
	List<User> sortedList = users.stream()
		.sorted(Comparator.comparing(User::getName))
		.collect(Collectors.toList());

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
15 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Masroor Ahmed
1 year ago

I always like your examples. All complicated issues solved by you in very simple examples.

PIP
3 months ago

{“ABC25”, “DEF10”, “GHI88”, “XYZ14”}

dgb
7 months ago

Wonderful Page! Simple and effective examples. Thanks so much!

Duong
3 years ago

How do I have your’s theme of code on this site, I’m interested in it so much.
Thank you a lot for your sharing.
Have a nice date!

Zohaan
3 years ago

Mind blowing mkyong…

Andres Piedra
3 years ago

Dears: a dummy and experimental question can be:
Why I need to do this:
Comparator.comparingInt(User::getAge)
Because I worked in apps wich got data directly order from SQL, so in what I need the data in memory in the back-end, end of the day, that would be main use of this? Since Java is a Backend Language, with a JavaScript part in the Front-End, in most of the cases.

Greetings

Nishanth
3 years ago

I have list of strings as below:
countries.add(“India”);
   countries.add(“Russia”);
   countries.add(“Italy”);
   countries.add(“England”);

I want to create a static method named “sortCountriesByName()” and
Sort the List using Comparator(Lambda Exp). Sort in the reverse alphabetical order

Please helpme

Marek
2 years ago
Reply to  Nishanth

public static void main(String[] args) {
List countries = new ArrayList();
countries.add(“India”);
countries.add(“Russia”);
countries.add(“Italy”);
countries.add(“England”);
System.out.println(sortCountriesByName(countries));
}

static List sortCountriesByName(List list){
return list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
}

Balaji Vinnakota
4 years ago

Hi,

I have a requirement where I should able to sort list of items from child object (Its a Set).

finalSortedAndPaginatedResult.stream()
.sorted(Comparator.comparing(((Function) RuleReferenceMaster::getDpRuleRefMappings)
.andThen(DatapointRuleMappingMaster::getPriority),Comparator.nullsFirst(Comparator.naturalOrder()))
.reversed())
.collect(Collectors.toList());

Where DatapointRuleMappingMaster is a Set

Annie
4 years ago

Hi,

While declaring User class as static I am getting below error.
“Illegal modifier for the class User; only public, abstract & final are permitted”
Could anyone please tell me, why I am getting this. I am using jdk 8 and eclipse IDE.

Thanks in advance!

Nabil
4 years ago

Hello ,
Thanks for this tutorial.
How to sort User using tow parameter age and name ?

Jorge Takeshi Sato
4 years ago
Reply to  Nabil

List sortedList = users.stream()
.sorted(Comparator.comparingInt(User::getAge).thenComparing(Comparator.comparing(User::getName)))
.collect(Collectors.toList());

Praveen Kumar
1 year ago

thenComparing is not working . Below is working code

List<User> sortedList = users.stream()
        .sorted(Comparator.comparingInt(User::getAge)).sorted(Comparator.comparing(User::getName))
        .collect(Collectors.toList());
Praveen Kumar
1 year ago
Reply to  Praveen Kumar

Sorry Your above code is also working fine

Carol
5 years ago

Thanks, very concrete.