Sort list of objects by field in Java 8
The Stream interface includes sorted() method that can be used to sort list of objects by natural order or by using a Comparator.
1) Sort list of objects by natural order using Stream sorted() method
// Stream Sort example package java8; import java.util.Arrays; import java.util.Comparator; import java.util.List; public class StreamSort { public static void main(String[] args) { List<String> actors = Arrays.asList("Tom", "Harry", "Mark"); actors.stream().sorted().forEach(System.out::println); } }
Console Output :
Harry Mark Tom
2) Sort list of objects by providing a Comparable order using Stream sorted() method
In this example we will sort list of Ball objects by name field.
// Stream Sort example package java8; import java.util.Arrays; import java.util.Comparator; import java.util.List; public class StreamSort { public static void main(String[] args) { Ball tennis = new Ball("tennis", 1, "green"); Ball footBall = new Ball("football", 2, "white"); Ball basketBall = new Ball("basketBall", 3, "orange"); List<Ball> balls = Arrays.asList(tennis, footBall, basketBall); balls.stream().sorted().forEach(System.out::println); } } class Ball implements Comparable<Ball> { private String name; private int size; private String color; // removed constructor, getters and setter for brevity @Override public String toString() { return "Ball [name=" + name + ", size=" + size + ", color=" + color + "]"; } public int compareTo(Ball ball) { return this.getName().compareTo(ball.getName()); } }
Console Output :
Ball [name=basketBall, size=3, color=orange] Ball [name=football, size=2, color=white] Ball [name=tennis, size=1, color=green]
3) Sort list of objects by calling Comparator comparing() method using any of the object field.
You can also sort the stream like this
package java8; import java.util.Arrays; import java.util.Comparator; import java.util.List; public class StreamSort { public static void main(String[] args) { Ball tennis = new Ball("tennis", 1, "green"); Ball footBall = new Ball("football", 2, "white"); Ball basketBall = new Ball("basketBall", 3, "orange"); List<Ball> balls = Arrays.asList(tennis, footBall, basketBall); balls.stream().sorted(Comparator.comparing(Ball::getSize)) .forEach(System.out::println); balls.stream().sorted(Comparator.comparing(Ball::getSize).reversed()) .forEach(System.out::println); } }
Ball [name=tennis, size=1, color=green] Ball [name=football, size=2, color=white] Ball [name=basketBall, size=3, color=orange] Ball [name=basketBall, size=3, color=orange] Ball [name=football, size=2, color=white] Ball [name=tennis, size=1, color=green]
You can also sort the stream like this
balls.stream().sorted(b1, b2 -> b1.getSize() - b2.getSize()) .forEach(System.out::println);
Console Output :
References :
Oracle Docs Stream sorted()
Oracle Docs Comparator comparing()