Lambda 表達式,也可稱爲閉包,它是推進 Java 8 發佈的最重要新特性。 Lambda 容許把函數做爲一個方法的參數(函數做爲參數傳遞進方法中)。 使用 Lambda 表達式能夠使代碼變的更加簡潔緊湊。bash
// item:能夠是任意值。相似於for循環中的循環值
dataList.forEach(item -> {
//設置值
item.setName(item.getName()+"測試");;
//輸出語句
System.out.println(item.toString());
});
}
複製代碼
sum(),max(),min(),average() 。閉包
mapToInt() 轉換成int。還有其餘類型轉換。如:double。函數
int rowCount = list.stream().mapToInt(Paper::getRow).sum();
複製代碼
Collectors.groupingBy(屬性名)測試
Map<Integer, List<Product>> map = list.stream().collect(Collectors.groupingBy(Product::getType));
複製代碼
Collectors.groupingBy(屬性,Collectors.groupingBy(屬性))ui
Map<String, Map<Integer, List<Product>>> map2 = list.stream().collect(Collectors.groupingBy(t->t.getName(),Collectors.groupingBy(t->t.getType())));
複製代碼
List<String> mapList1 = list.stream().map(Product::getName).collect(Collectors.toList());
List<String> mapList2 = list.stream().map(item->item.getName()).collect(Collectors.toList());
複製代碼
filter(item->{}) item爲每一項。 按照本身的需求來篩選list中的數據spa
List<Person> filterList = list.stream().filter(item->item.getPrice()>100).collect(Collectors.toList());
複製代碼
distinct() 去重;collect(Collectors.toList())。封裝成集合code
List<Product> distinctList = list.stream().distinct().collect(Collectors.toList());
複製代碼
String names = testDemos.stream().map(TestDemo::getName).collect(Collectors.joining(","));
複製代碼
list2 = list1.stream().map(user->{return user.getRealName();}).collect(Collectors.toList());
複製代碼
Map<String, String> educationMap = educationList.stream().collect(Collectors.toMap(SystemOption::getName, b -> b.getCode(), (k1, k2) -> k1));
複製代碼
Double count = list.stream().mapToDouble(CreditFractionRecord::getFr_score).sum();
複製代碼
Map<Long, Student> studentMap = studentList.stream().collect(Collectors.toMap(Student::getId, (k) -> k));
複製代碼