Skip to content

Instantly share code, notes, and snippets.

@YukiYoshikawa
Last active December 16, 2015 07:59
Show Gist options
  • Save YukiYoshikawa/5402618 to your computer and use it in GitHub Desktop.
Save YukiYoshikawa/5402618 to your computer and use it in GitHub Desktop.
package trial.yy.java8.client.lambda;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Java8 ラムダ式をComapratorに適用して試すためのサンプル
* User: yy
* Date: 13/04/17
* Time: 22:00.
*/
public class Java8CompareClient {
public static void main(String[] args) {
// 操作対象の文字列を格納したList
List<String> srcList = Arrays.asList("defg", "defg", "x", "xyz", "zzzzzzzz", "abc", "abcde");
List<String> srcList1 = new ArrayList(srcList);
List<String> srcList2 = new ArrayList(srcList);
// 比較関数をラムダ式で記述(文字列のlength順に並べるための比較関数)
Comparator<String> comparator = (x, y) -> x.length() - y.length();
// 比較関数を適用してソート実行
Collections.sort(srcList1, comparator);
// ソートした結果を出力
System.out.println("srcList1: " + srcList1);
// 比較関数をラムダ式で記述して直接sortのAPIに渡してソート実行
Collections.sort(srcList2, (x, y) -> x.length() - y.length());
// ソートした結果を出力
System.out.println("srcList2: " + srcList2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment