Java Stream How to - Sort with Lambda








The following code shows how to sort with Lambda.

Example

//from   w ww . jav a  2  s.  c  o m
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

    public static void main(String...args){
        List<Apple> inventory = new ArrayList<>();
        inventory.addAll(Arrays.asList(new Apple(80,"green"), new Apple(155, "green"), new Apple(120, "red")));

        inventory.sort((a1, a2) -> a1.getWeight().compareTo(a2.getWeight()));
        System.out.println(inventory);
    }
}
class Apple {
  private Integer weight = 0;
  private String color = "";

  public Apple(Integer weight, String color){
      this.weight = weight;
      this.color = color;
  }

  public Integer getWeight() {
      return weight;
  }

  public void setWeight(Integer weight) {
      this.weight = weight;
  }

  public String getColor() {
      return color;
  }

  public void setColor(String color) {
      this.color = color;
  }

  public String toString() {
      return "Apple{" +
             "color='" + color + '\'' +
             ", weight=" + weight +
             '}';
  }
}

The code above generates the following result.