給定一個 List<A>,其中 A 類別包含 id 與 name 欄位,需將所有元素的 id 提取並組成 List<Integer>,不需過濾。
List<A> list = new ArrayList<>();
// ... 填充資料
List<Integer> ids = list.stream()
.map(A::getId)
.collect(Collectors.toList());
stream():將集合轉為流。map(A::getId):使用方法引用,等同 a -> a.getId(),程式碼更優雅。collect(Collectors.toList()):將流收集為 List。List<Integer> ids = list.stream()
.map(a -> a.getId())
.collect(Collectors.toList());
兩種寫法效能相同,方法引用更符合函數式風格,推薦優先使用。