Created
July 28, 2012 07:21
-
-
Save miyakawataku/3192234 to your computer and use it in GitHub Desktop.
Sort an array of integers using an anonymous class or a lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Comparator; | |
public class Sort { | |
public static void main(String[] args) { | |
// [0, 1000) の整数列 | |
Integer[] numbers = new Integer[10]; | |
for (int index = 0; index < numbers.length; ++ index) | |
numbers[index] = (int) (Math.random() * 1000); | |
// 整数列を降順でソート: これまで通り匿名クラスを使う場合 | |
Arrays.sort(numbers, new Comparator<Integer>() { | |
@Override public int compare(Integer x, Integer y) { | |
return y - x; | |
} | |
}); | |
// 整数列を降順でソート: Java 8 の Lambda 式を使う場合 | |
Arrays.sort(numbers, (x, y) -> y - x); | |
// ソートされた整数列を表示 | |
for (int number : numbers) | |
System.out.println(number); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment