Stream
流式操作
Stream
流式操作,就是學習java.util.stream
包下的API
,Stream
不同于java
的輸入輸出流,是實現對集合(Collection)
的復雜操作,例如查找、替換、過濾和映射數據等,集合是一種靜態的數據結構,存儲在內存中,而Stream
是用于計算的,通過CPU
實現計算,因此可以認為Stream
就是處理集合數據的各種算法流程。
Stream
流式操作流程
Stream流式操作主要有 3 個步驟:
1、創建Stream對象
:通過一些數據源創建流對象
2、中間操作
:對數據源的數據進行處理(過濾、排序等)
3、終止操作
:一旦執行終止操作, 就執行中間的鏈式操作,并產生結果
Stream
的獲取
1.針對集合:Collection中的方法Stream<E> stream() 2.針對數組:Stream接口中的靜態方法:static <T> Stream<T> of(T... values)
Stream
的操作
準備需要操作的集合
// 由數字組成的集合
List<Integer> numberList = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5);// Student類:自增的主鍵id,name由uuid生成,且首位是數字
List<Student> selectList = studentMapper.selectList(new LambdaQueryWrapper<>());
Stream
的中間操作
// filter:過濾
// 截取首位數字,輸出取余為0的對象
List<Student> list1 = selectList.stream().filter(student -> {int i = Integer.parseInt(student.getName().substring(0, 1));return 0 == (i % 2);
}).collect(Collectors.toList());
// map:將流中的每個元素映射為另一個元素,生成一個新的流
// 輸出每個Student
List<Integer> list2 = selectList.stream().map(student -> student.getName().length()).collect(Collectors.toList());
// sorted:對流中的元素進行排序,默認是自然順序排序,也可以傳入Comparator進行自定義排序
// 集合中是一個對象
// 根據id正序
List<Student> list3 = selectList.stream().sorted(Comparator.comparing(Student::getId)).collect(Collectors.toList());
// 根據id倒敘
List<Student> list4 = selectList.stream().sorted(Comparator.comparing(Student::getId).reversed()).collect(Collectors.toList());
// 集合中是數字
List<Integer> list5 = numberList.stream().sorted((o1, o2) -> {if (o1.compareTo(o2) > 0) {return -1;} else {return 1;}
}).collect(Collectors.toList());
// distinct:去重
List<Integer> list6 = numberList.stream().distinct().collect(Collectors.toList());
// limit:截取前幾個元素
List<Integer> list7 = numberList.stream().limit(3).collect(Collectors.toList());
// skip:越過前幾個元素
List<Integer> list8 = numberList.stream().skip(3).collect(Collectors.toList());
Stream
的終止操作
// forEach:遍歷操作,沒有返回值,在accept方法中編寫集合處理邏輯即可
selectList.forEach(new Consumer<Student>() {@Overridepublic void accept(Student student) {System.err.println(student.getId()+" -- "+student.getName())}
});
// 可簡化為
selectList.forEach(student -> System.err.println(student.getId()+" -- "+student.getName()));
// collect:將流中的元素收集到一個集合中。可以通過Collectors工具類提供的方法來實現不同類型的收集操作。
// 例如:從查詢到的所有學生中,過濾id>10的,然后將過濾出來的所有學生放進一個新的集合中
List<Student> studentList = selectList.stream().filter(student -> student.getId() > 10).collect(Collectors.toList());
// reduce:對流中的元素求和
int sum = numberList.stream().reduce(0, Integer::sum);
// count:統計個數
long count = numberList.stream().count();
// anyMatch:判斷流中是否存在任意一個元素滿足給定條件。
boolean anyMatch = numberList.stream().anyMatch(integer -> integer % 2 == 0);
// anyMatch:判斷流中的所有元素是否都滿足給定條件。
boolean allMatch = numberList.stream().allMatch(integer -> integer % 2 == 0);