Java Stream How to - Sort all graduates from year 2011








The following code shows how to sort all graduates from year 2011.

Example

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
// ww  w . j a  va 2 s  .co m
public class Main {
  public static void main(String...args){
    Student raoul = new Student("Raoul", "Cambridge");
    Student mario = new Student("Mario","Milan");
    Student alan = new Student("Alan","Cambridge");
    Student brian = new Student("Brian","Cambridge");
    
    List<Graduate> transactions = Arrays.asList(
        new Graduate(brian, 2011, 300), 
        new Graduate(raoul, 2012, 1000),
        new Graduate(raoul, 2011, 400),
        new Graduate(mario, 2012, 710),  
        new Graduate(mario, 2012, 700),
        new Graduate(alan, 2012, 950)
    );  
    
    List<Graduate> tr2011 = transactions.stream()
                                           .filter(transaction -> transaction.getYear() == 2011)
                                           .sorted(Comparator.comparing(Graduate::getValue))
                                           .collect(Collectors.toList());
    System.out.println(tr2011);
    
    
  }
}
class Student{
  
  private String name;
  private String city;

  public Student(String n, String c){
      this.name = n;
      this.city = c;
  }

  public String getName(){
      return this.name;
  }

  public String getCity(){
      return this.city;
  }

  public void setCity(String newCity){
      this.city = newCity;
  }

  public String toString(){
      return "Student:"+this.name + " in " + this.city;
  }
}

class Graduate{

  private Student trader;
  private int year;
  private int value;

  public Graduate(Student trader, int year, int value)
  {
      this.trader = trader;
      this.year = year;
      this.value = value;
  }

  public Student getTrader(){ 
      return this.trader;
  }

  public int getYear(){
      return this.year;
  }

  public int getValue(){
      return this.value;
  }
  
  public String toString(){
      return "{" + this.trader + ", " +
             "year: "+this.year+", " +
             "value:" + this.value +"}";
  }
}

The code above generates the following result.