最近在做項目的過程中經常會接觸到 lambda 表達式,隨後發現它基本上可以替代所有 for 循環,包括增強for循環。也就是我認爲,絕大部分的for循環都可以用 lambda 表達式改寫。
lambda表達式有它自己的優點:(1)簡潔,(2)易並行計算。尤其適用於遍歷結果,循環計算數值或者賦值的時候非常方便。
缺點: (1)若不用並行計算,很多時候計算速度沒有比傳統的 for 循環快。
(2)不容易使用debug模式調試。
(3)在 lambda 語句中直接強制類型轉換不方便。
(4)不可以在foreach中修改foreach外面的值。
public class Jdk8Main {
public static void main(String[] args) {
List<Person> list = new ArrayList<>();
Person p1 = new Person("張1",1,1);
Person p101 = new Person("張101",101,101);
Person p2 = new Person("張2",2,2);
Person p3 = new Person("張3",3,3);
Person p4 = new Person("張4",4,4);
Person p5 = new Person("張5",5,5);
Person p6 = new Person("張6",6,6);
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
list.add(p5);
list.add(p6);
list.add(p101);
/**
* 1.forEach()進行遍歷集合
* item:可以是任意值。類似於for循環中的循環值
*/
list.forEach(item->{
//設置值
item.setName(item.getName()+"測試");;
//輸出語句
System.out.println(item.toString());
});
/**
* 2.stream()流操作
*/
//2.1. 去重 distinct() 去重;collect(Collectors.toList())。封裝成集合
List<Person> distinctList =
list.stream().distinct().collect(Collectors.toList());
//2.2 排序 sorted((第一個對象,第二個對象)->返回值) (升降序看是第幾個對象與第幾個對象比較)
List<Person> sortedList = list.stream().sorted((o1,o2)->o1.getAge()-o2.getAge()).collect(Collectors.toList());
//2.3 過濾 , filter(item->{}) item爲每一項。 按照自己的需求來篩選list中的數據
List<Person> filterList = list.stream().filter(item->item.getAge()>3).collect(Collectors.toList());
//2.4 map(), 提取對象中的某一元素. 用每一項來獲得屬性(也可以直接用 對象::get屬性())
List<String> mapList1 = list.stream().map(Person::getName).collect(Collectors.toList());
List<String> mapList2 = list.stream().map(item->item.getName()).collect(Collectors.toList());
//2.5 統計 sum() 。mapToDouble() 轉換成double。還有其他類型轉換。可以自己研究。
// max(),min(),average()
double sum = list.stream().mapToDouble(Person::getAge).sum();
//2.6 分組 Collectors.groupingBy(屬性名)
Map<Integer, List<Person>> map = list.stream().collect(Collectors.groupingBy(Person::getAge));
//2.7 多重分組 Collectors.groupingBy(屬性,Collectors.groupingBy(屬性))
Map<String, Map<Integer, List<Person>>> map2 = list.stream().collect(Collectors.groupingBy(t->t.getName(),Collectors.groupingBy(t->t.getAge())));
//2.8 分組並計算綜合 Collectors.summarizingLong()
Map<String, Map<Integer, LongSummaryStatistics>> map3 = list.stream().collect(Collectors.groupingBy(t->t.getName(),Collectors.groupingBy(t->t.getAge(),Collectors.summarizingLong(Person::getSize))));
/**
* 3. 集合比較的簡寫方式
*/
list.sort((o1,o2)->{return o1.getAge()-o2.getAge();});
}
}