# 認識 Lambda/Closure（5）Java 的稻草人提案

English

``````// asList 與 sort 方法是從 Arrays 與 Collections 中 static import 而來
List<Integer> numbers = asList(3, 2, 6, 4);
sort(numbers, new Comparator<Integer>() {
public int compare(Integer n1, Integer n2) {
return -n1.compareTo(n2);
}
});``````

``````List<Integer> numbers = asList(3, 2, 6, 4);

Comparator<Integer> descending = new Comparator<Integer>() {
public int compare(Integer n1, Integer n2) {
return -n1.compareTo(n2);
}
};

sort(numbers, descending);``````

``````List<Integer> numbers = asList(3, 2, 6, 4);
sort(numbers, (n1, n2) -> -n1.compareTo(n2));``````

``````public static FactorProducer createFactorProducer(max) {
final int[] primes = ...;
FactorProducer producer = new FactorProducer() {
public int factor() {
...
while(pow(primes[i], 2)) {
...
}
}
};
return producer;
}``````

``````var sum = 0;
[1, 2, 3, 4, 5].forEach(function(elem) {
sum += elem;
});``````

``````#int(int) doubler = #(int x)(2 * x);
doubler.(3) // 呼叫 Lambda``````

``````int doubler(int x) {
return 2 * x;
}
doubler(3);``````

``#int(int, int) sum = #(int x, int y)(x + y)``

``````int sum(int x, int y) {
return x + y;
}``````

``````def bubbleSort(int[] arr, #boolean(int, int) order) {
...
boolean o = order.(a, b);
...
}
int[] arr = new int[] {2, 5, 1, 7, 8};
bubbleSort(arr, #(int a, int b)(a > b));``````

``##int(int)(int) sum = #(int x)(#(int y)(x + y));``