This article contains Java 8 Stream sorted Examples. Java 8 Stream provide two version of sorted method to sort given stream to natural order and sort stream based on comparator.

Natural ordering uses the ordering provided by Comparable which must be implemented by the class whose instances are the stream elements.

In this article we are going to discuss various usage of stream class sorted method.

  1. Primitive type natural order sorting
  2. User defined object sorting / Sorting using comparator
  3. Reverse sorting / Descending order sorting
  4. Sort List  by employee gender
  5. Sort Set by employee designation

Now let’s discuss each one in details.

1) Primitive type natural order sorting

//Build IntStream
IntStream intStream = IntStream.of(3, 2, 1, 2, 5);
System.out.println("Sort IntStream");
intStream.sorted().forEach(x -> System.out.print(x+","));//natural order sort & print

//Build list of numbers
List<Integer> numbers = Arrays.asList(3, 2, 1, 2, 5);
System.out.println(System.lineSeparator()+"Sort list of int numbers");
numbers.stream().sorted().forEach(x -> System.out.print(x+",")); //natural order sort & print

Output

 Sort IntStream
1,2,2,3,5,
Sort list of int numbers
1,2,2,3,5,

2 ) User defined object sorting / Sorting using comparator

List<Employee> employeeList = Employee.getEmployee();
System.out.println("---Natural Sorting by Employee No---");
List<Employee> slist = employeeList.stream().sorted(Comparator.comparing(Employee::getNo)).collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:"+ e.getNo()+", Name: "+e.getName()));

Output

---Natural Sorting by Employee No---
Id:1, Name: Bob
Id:2, Name: Joy
Id:3, Name: John
Id:4, Name: Bat
Id:5, Name: Jolly
Id:6, Name: Bobby

3) Reverse sorting / Descending order sorting

//Build list of numbers
List<Integer> numbers = Arrays.asList(3, 2, 1, 2, 5);
System.out.println(System.lineSeparator()+"Sort list of int numbers");
numbers.stream().sorted(Comparator.reverseOrder()).forEach(x -> System.out.print(x+",")); //reverse order sort & print

Output

Sort list of int numbers
5,3,2,2,1

4) Sort List  by employee gender

List<Employee> employeeList = Employee.getEmployee();

System.out.println("---Sorting using Comparator by Gender--");
List<Employee> slist = employeeList.stream().sorted(Comparator.comparing(Employee::getGender)).collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:"+ e.getNo()+", Name: "+e.getName()+", Gender:"+e.getGender()));

Output

---Sorting using Comparator by Gender--
Id:5, Name: Jolly, Gender:Female
Id:6, Name: Bobby, Gender:Female
Id:1, Name: Bob, Gender:Male
Id:2, Name: Joy, Gender:Male
Id:3, Name: John, Gender:Male
Id:4, Name: Bat, Gender:Male

 5) Sort Set by employee designation

HashSet<Employee> employeeSet = new HashSet<>(Employee.getEmployee());

System.out.println("---Sorting using Comparator by Designation---");
List<Employee> slist= employeeSet.stream().sorted(Comparator.comparing(Employee::getDesignation)).collect(Collectors.toList());
slist.forEach(e -> System.out.println("Id:"+ e.getNo()+", Name: "+e.getName()+", Designation:"+e.getDesignation()));

Output:

---Sorting using Comparator by Designation---
Id:3, Name: John, Designation:CEO
Id:1, Name: Bob, Designation:Developer
Id:4, Name: Bat, Designation:Developer
Id:6, Name: Bobby, Designation:Developer
Id:5, Name: Jolly, Designation:Developer
Id:2, Name: Joy, Designation:Sr. Developer

Employee – POJO Class

public class Employee implements Comparable<Employee>{
    private int no;
    private String name;
    private String designation;
    private String gender;
    private Set<String> languages;

    public Set<String> getLanguages() {
        return languages;
    }

    public Employee(int no, String name, String designation, String gender , String [] languages) {
        this.no = no;
        this.name = name;

        this.designation = designation;
        this.gender = gender;
        this.languages = new HashSet<>(Arrays.asList(languages));
    }

    public void addLanguage(String language){
        this.languages.add(language);
    }
  
  //getter , setter methods
    @Override
    public String toString() {
        return this.no + " : " + this.name + " : " + gender + " : " + designation;
    }

    @Override
    public int hashCode() {
        int hashno = 7;
        hashno = 13 * hashno + (name == null ? 0 : name.hashCode());
        return hashno;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        final Employee std = (Employee) obj;
        if (this == std) {
            return true;
        } else {
            return (this.name.equals(std.name)
                    && (this.no == std.no)) && (this.designation.equals(std.designation))
                    && (this.gender.equals(std.gender));
        }
    }

    public static java.util.List<Employee> getEmployee() {
        java.util.List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1, "Bob", "Developer", "Male",new String[]{"java","scala"}));
        employees.add(new Employee(2, "Joy", "Sr. Developer", "Male",new String[]{"java"}));
        employees.add(new Employee(3, "John", "CEO", "Male",new String[]{"python","ruby"}));
        employees.add(new Employee(4, "Bat", "Developer", "Male",new String[]{"scala"}));
        employees.add(new Employee(5, "Jolly", "Developer", "Female",new String[]{"C","C++"}));
        employees.add(new Employee(6, "Bobby", "Developer", "Female",new String[]{".Net","VB"}));
        return employees;
    }

    @Override
    public int compareTo(Employee o) {
        return name.compareTo(o.getName());
    }

Refer Stream basic , Stream Sorted for more details.

 

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

Your email address will not be published. Required fields are marked *