Java Stream是一個用于處理集合資料的新工具,它是某些功能的精簡替代,如聚合和篩選。
Java Stream API操作可以分為以下步驟:
1.建立 Stream: 一個資料源(如:集合、數組),擷取一個流。
2.中間操作:對資料源進行篩選、切片、排序等操作
3.終止操作:執行操作後,生成結果。
以下是常用方法介紹:
1.建立 Stream:
// 1. 通過集合建立 Stream
List<String> list = new ArrayList<>();
Stream<String> stream1 = list.stream();
// 2. 通過數組建立 Stream
int[] arr = {1, 2, 3};
IntStream stream2 = Arrays.stream(arr);
// 3. 通過 Stream 的 of 方法建立
Stream<String> stream3 = Stream.of("a", "b", "c");
// 4. 通過 Stream 的 iterate 方法建立
Stream<Integer> stream4 = Stream.iterate(0, n -> n + 2)
// 5. 通過 Stream 的 generate 方法建立
Stream<Double> stream5 = Stream.generate(Math::random);
2.中間操作:
// 1. filter:過濾,傳回一個新的 Stream
Stream<Integer> stream1 = stream.filter(i -> i > 0);
// 2. map:映射,傳回一個新的 Stream
Stream<Integer> stream2 = stream.map(i -> i * 2);
// 3. flatMap:扁平化,傳回一個新的 Stream
Stream<String> stream3 = Stream.of("a,b,c", "d,e,f").flatMap(s -> Arrays.stream(s.split(",")));
// 4. distinct:去重,傳回一個新的 Stream
Stream<Integer> stream4 = stream.distinct();
// 5. sorted:排序,傳回一個新的 Stream
Stream<Integer> stream5 = stream.sorted();
// 6. peek:對每個元素執行操作,傳回一個新的 Stream
Stream<String> stream6 = stream.peek(System.out::println);
// 7. limit:限制傳回個數,傳回一個新的 Stream
Stream<Integer> stream7 = stream.limit(3);
// 8. skip:跳過前幾個元素,傳回一個新的 Stream
Stream<Integer> stream8 = stream.skip(2);
3.終止操作:
// 1. forEach:周遊元素
stream.forEach(System.out::println);
// 2. count:計算元素個數
long count = stream.count();
// 3. collect:将元素收集到集合中
List<String> list = stream.collect(Collectors.toList());
Set<String> set = stream.collect(Collectors.toSet());
// 4. reduce:歸約操作
Optional<Integer> result = stream.reduce((a, b) -> a + b);
// 5. max/min:查找最大/最小值
Optional<Integer> max = stream.max(Comparator.naturalOrder());
Optional<Integer> min = stream.min(Comparator.naturalOrder());
// 6. allMatch/anyMatch/noneMatch:判斷是否有元素比對
boolean allMatch = stream.allMatch(i -> i > 0);
boolean anyMatch = stream.anyMatch(i -> i > 0);
boolean noneMatch