Java 8 Stream - sorted() method example

Posted on February 20, 2017


The following examples demonstrate  how the sorted() method of java.util.stream.Stream is used to sort the elements of a stream.

Example #1

Here is an example of using Stream.sorted() to sort elements of a stream.

StreamSortedExample1.java

package com.boraji.tutorial;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author imssbora
 */
public class StreamSortedExample1 {
   public static void main(String[] args) {
      List<Integer> numbers=new ArrayList<>();
      numbers.add(10);
      numbers.add(44);
      numbers.add(15);
      numbers.add(23);
      numbers.add(35);
      numbers.add(14);
      numbers.add(17);
      
      Stream<Integer> stream=numbers.stream();
      stream.sorted().forEach(n->{System.out.println(n);});
   }
}

Output

10
14
15
17
23
35
44

Example #2

The following example sort the users objects on the basis of their age using Stream.sort() method.

StreamSortedExample2.java

package com.boraji.tutorial;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author imssbora
 */

class User {
   private int id;
   private String name;
   private int age;

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

   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   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;
   }
}

public class StreamSortedExample2 {
   public static void main(String[] args) {
      List<User> users = new ArrayList<>();
      users.add(new User(1, "Manni", 28));
      users.add(new User(2, "Rama", 15));
      users.add(new User(3, "Peter", 40));
      users.add(new User(4, "Mini", 25));
      users.add(new User(5, "Ajay", 45));

      Stream<User> stream = users.stream();
      stream.sorted((user1, user2) -> {
         return (user1.getAge() - user2.getAge());
      }).forEach(u -> {
         System.out.println("ID:" + u.getId() + "\t Name:" + u.getName() 
            + "\t Age:" + u.getAge());
      });
   }
}

Output

ID:2	 Name:Rama	 Age:15
ID:4	 Name:Mini	 Age:25
ID:1	 Name:Manni	 Age:28
ID:3	 Name:Peter	 Age:40
ID:5	 Name:Ajay	 Age:45