Java8のLambda式でオブジェクトの比較・ソートをお手軽に

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TryLambda{
  public static void main(String[] args){
    List<MyData> myList = new ArrayList<MyData>();
    myList.add(new MyData(5, 9));
    myList.add(new MyData(3, 8));
    myList.add(new MyData(4, 7));
    myList.add(new MyData(1, 6));
    myList.add(new MyData(2, 5));

    System.out.println("Before sort: " + myList);

    //Lambda式でCompareの処理を定義
    Collections.sort(myList, (o1, o2) -> Integer.compare(o1.comp, o2.comp));

    System.out.println("After sort: " + myList);
  }
}

class MyData{
  int comp;
  int ignore;
  public MyData(int comp, int ignore) {
    this.comp = comp;
    this.ignore = ignore;
  }

  public String toString(){
    return "(comp: " + Integer.toString(comp) + ", " + "ignore: " + ignore + ")";  
  }
}

実行結果

Before sort: [(comp: 5, ignore: 9), (comp: 3, ignore: 8), (comp: 4, ignore: 7), (comp: 1, ignore: 6), (comp: 2, ignore: 5)]
After sort: [(comp: 1, ignore: 6), (comp: 2, ignore: 5), (comp: 3, ignore: 8), (comp: 4, ignore: 7), (comp: 5, ignore: 9)]