Lambda Expressions กับ Collections
Java 8+ รองรับ Lambda Expressions สำหรับ Functional Interfaces (Single Abstract Method) ทำให้โค้ดสั้นและอ่านง่าย
1. เรียงลำดับ List ด้วย Lambda
import java.util.*;
public class Demo {
public static void main(String[] args) {
List list = new ArrayList<>(Arrays.asList(190, 267, 12, 0));
System.out.println("ก่อนเรียง: " + list);
// Descending order: (o1, o2) -> o2 - o1 หรือใช้ Comparator.reverseOrder()
list.sort((o1, o2) -> o2 - o1);
System.out.println("หลังเรียง (Desc): " + list);
// Ascending (default)
list.sort(Integer::compareTo);
System.out.println("หลังเรียง (Asc): " + list);
// Custom object sorting
List words = Arrays.asList("banana", "apple", "cherry");
words.sort((s1, s2) -> s1.length() - s2.length()); // sort by length
System.out.println("เรียงตามความยาว: " + words);
}
}
ผลลัพธ์
ก่อนเรียง: [190, 267, 12, 0] หลังเรียง (Desc): [267, 190, 12, 0] หลังเรียง (Asc): [0, 12, 190, 267] เรียงตามความยาว: [apple, banana, cherry]
2. TreeMap ด้วย Lambda Comparator
import java.util.*;
public class Demo {
public static void main(String[] args) {
// TreeMap กำหนด Comparator ด้วย Lambda (Descending key)
TreeMap map = new TreeMap<>((k1, k2) -> k2 - k1);
map.put(56, "Joe");
map.put(43, "Bill");
map.put(21, "Charlotte");
map.put(33, "Jonas");
System.out.println("TreeMap (Descending keys): " + map);
// NavigableMap operations
System.out.println("First (highest key): " + map.firstEntry());
System.out.println("Last (lowest key): " + map.lastEntry());
System.out.println("SubMap 30-50: " + map.subMap(30, true, 50, true));
}
}
ผลลัพธ์
TreeMap (Descending keys): {56=Joe, 43=Bill, 33=Jonas, 21=Charlotte}
First (highest key): 56=Joe
Last (lowest key): 21=Charlotte
SubMap 30-50: {43=Bill, 33=Jonas}
Lambda Syntax Patterns
| Pattern | Syntax | Example |
|---|---|---|
| No params | () -> expr | () -> System.out.println("hi") |
| One param | x -> expr | x -> x * 2 |
| Multiple params | (x, y) -> expr | (a, b) -> a + b |
| Block body | (x, y) -> { ... return z; } | (a, b) -> { int c = a+b; return c; } |
| Method Reference | Class::method | Integer::compareTo |
| Constructor Ref | Class::new | ArrayList::new |
Comparator Static Methods (Java 8+)
// แทน lambda แบบ manual
list.sort((a, b) -> a - b); // ascending
list.sort((a, b) -> b - a); // descending
// ใช้ built-in
list.sort(Comparator.naturalOrder()); // ascending
list.sort(Comparator.reverseOrder()); // descending
list.sort(Comparator.nullsFirst(...)); // nulls first
list.sort(Comparator.comparing(Person::getName)); // by field
list.sort(Comparator.comparingInt(Person::getAge)); // by int field
// Chaining
list.sort(Comparator
.comparing(Person::getLastName)
.thenComparing(Person::getFirstName)
.reversed());
Stream API กับ Lambda
Listresult = list.stream() .filter(s -> s.length() > 3) .map(String::toUpperCase) .sorted() .collect(Collectors.toList());
ข้อควรระวัง
- Lambda ต้องเป็น Functional Interface (SAM type)
- Variable capture: ต้องเป็น effectively final
- Serialization: Lambda Serializable ได้ก็ต่อเมื่อ target type Serializable
- Debugging: Stack trace แสดง lambda เป็น
Demo$$Lambda$1/0x0000...