Java Lambda表達式示例(偶爾更新)

Lambda 表達式,也可稱爲閉包,它是推進 Java 8 發佈的最重要新特性。 Lambda 容許把函數做爲一個方法的參數(函數做爲參數傳遞進方法中)。 使用 Lambda 表達式能夠使代碼變的更加簡潔緊湊。bash

1、利用流和Lambda表達式對List集合進行處理

1.List集合遍歷

// item:能夠是任意值。相似於for循環中的循環值
   dataList.forEach(item -> {
              //設置值
             item.setName(item.getName()+"測試");;
             //輸出語句
             System.out.println(item.toString());  
                });
            }
複製代碼

2.統計List集合

sum(),max(),min(),average() 。閉包

mapToInt() 轉換成int。還有其餘類型轉換。如:double。函數

int rowCount = list.stream().mapToInt(Paper::getRow).sum();
複製代碼

3.對List集合分組

Collectors.groupingBy(屬性名)測試

Map<Integer, List<Product>> map = list.stream().collect(Collectors.groupingBy(Product::getType));
複製代碼

4.多重分組

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())));
複製代碼

5.map(), 提取對象中的某一元素. 用每一項來得到屬性(也能夠直接用 對象::get屬性())

List<String> mapList1 = list.stream().map(Product::getName).collect(Collectors.toList());
         List<String> mapList2 = list.stream().map(item->item.getName()).collect(Collectors.toList());
複製代碼

6.過濾

filter(item->{}) item爲每一項。 按照本身的需求來篩選list中的數據spa

List<Person> filterList = list.stream().filter(item->item.getPrice()>100).collect(Collectors.toList());
複製代碼

7. 去重

distinct() 去重;collect(Collectors.toList())。封裝成集合code

List<Product> distinctList = list.stream().distinct().collect(Collectors.toList());
複製代碼

8.List對象中的屬性以逗號分隔轉字符串

String names = testDemos.stream().map(TestDemo::getName).collect(Collectors.joining(","));
複製代碼

9. 把一個對象list的元素放到另一個list

list2 = list1.stream().map(user->{return user.getRealName();}).collect(Collectors.toList());
複製代碼

10.將對象list中的屬性轉換爲Map鍵值對

Map<String, String> educationMap = educationList.stream().collect(Collectors.toMap(SystemOption::getName, b -> b.getCode(), (k1, k2) -> k1));
複製代碼

11.對象list求和

Double count = list.stream().mapToDouble(CreditFractionRecord::getFr_score).sum();
複製代碼

12.將對象list中的轉換爲Map<id,對象>

Map<Long, Student> studentMap = studentList.stream().collect(Collectors.toMap(Student::getId, (k) -> k));
複製代碼
相關文章
相關標籤/搜索