//生成字符數組
List<String> list = Arrays.asList("a", "b", "c", "d");
//變大寫
List<String> stringList = list.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(stringList);//[A, B, C, D]
//數組
List<Integer> num = Arrays.asList(1,2,3,4,5);
//2倍
List<Integer> num2 = num.stream().map(n -> n * 2).collect(Collectors.toList());
System.out.println(num2);//[2, 4, 6, 8, 10]
/**
* Student(Id, name)
* studentList[{1, zhangsan}, {2, lisi}]
*/
//獲取學生數組中的每個學生id
List<String> studentIds = studentList.stream().map(Student::getStudentId).collect(Collectors.toList());
System.out.println(studentIds );//[1, 2]
正常的思路是遍歷list取出每個需要的值,是沒問題的,不過使用stream()效率更高
stream()優點
-
無存儲。stream不是一種數據結構,它只是某種數據源的一個視圖,數據源可以是一個數組,Java容器或I/O channel等。
-
爲函數式編程而生。對stream的任何修改都不會修改背後的數據源,比如對stream執行過濾操作並不會刪除被過濾的元素,而是會產生一個不包含被過濾元素的新stream。
-
惰式執行。stream上的操作並不會立即執行,只有等到用戶真正需要結果的時候纔會執行。
-
可消費性。stream只能被“消費”一次,一旦遍歷過就會失效,就像容器的迭代器那樣,想要再次遍歷必須重新生成。