說明java
stream 操做的數據源爲:集合、數組 。流講的是計算數組
1. stream 本身不會在存儲元素app
2. stream 不會改變源對象。相反他們會返回一個持有結果的新streamdom
3. stream 操做是延時執行的。這意味豐他們會等到須要結果的時候才執行ide
流的建立this
//1 .經過 collection 集合提供的 stream()【串行】 和 parallelStream()【並行】 List<String> list = new ArrayList<>(); list.stream(); //2. 經過 Arrays 中靜態方法 stream() 獲取數組流 Arrays.stream("a,b,c".split(",")); //3. 經過Stream 類中的靜態方法 of Stream.of("a", "b", "c"); //4. 建立無限流 Stream.iterate(0,(x) -> x+2); Stream.generate(Math::random);
中間操做 (不會生成任何結果)spa
1. 篩選code
filter : 過濾對象
limit : 截取排序
skip :獲取前 N個元素
distinct :去重
只選擇 >0.5的隨機數。只獲取10個,跳過前3個元素,排除相同的元素
Stream.generate(Math::random) .filter((x) -> x > 0.5) .limit(10) .skip(3) .distinct();
2. 映射 (map)
將 double 轉成 int 類型
Stream.generate(Math::random) .map((x) -> (int) (x * 100)).limit(10) .forEach(System.out::println);
flatMap 將流中的每個值都換成另外一個流,把全部的流都鏈接成一個流
3.排序 (sorted)
Stream.generate(Math::random) .sorted() ;
list.stream() .sorted(Comparator.comparing(Apple::getName)) .collect(Collectors.toList());
終止操做
stream 【終止操做】纔會生成結果,【中間操做】不會
anyMatch : 至少匹配一個元素
allMatch : 匹配全部元素
noneMatch:沒有匹配全部元素
findFirst :獲取第一個元素
findAny :獲取任意元素
count :獲取元素數量
max :獲取元素中的最大值
min:獲取元素中的最小值
將 1,2,3,4,5 累加起來
int total = Stream.of(1, 2, 3, 4, 5) .reduce(0, (x, y) -> x + y); Optional<Integer> total = Stream.of(1, 2, 3, 4, 5) .reduce(Integer::sum);
List<Integer> code = Stream.of("Mary", "Jack", "Water", "Amy", "Jame") .map(String::hashCode) .collect(Collectors.toList()); //放在 ArrayList中 List<Integer> code = Stream.of("Mary", "Jack", "Water", "Amy", "Jame") .map(String::hashCode) .collect(Collectors.toCollection(ArrayList::new));
Collectors.groupingBy(); //分組
Collectors.maxBy(); //最大值
Collectors.minBy(); //最小值
Collectors.toCollection(); //生成指定集合
Collectors.toList(); //生成list
Collectors.toSet(); //生成set
Collectors.counting(); //元素個數
Collectors.joining(); //字符串鏈接
Collectors.partitioningBy(); //分區
Collectors.summingInt(); //求和
Collectors.toMap(); //
Collectors.summarizingInt();//
Collectors.reducing();
Collectors.mapping();
案例
list.stream().map(Apple::getName) .filter(Objects::nonNull) //選擇不爲null的Apple .distinct() //不能重複 .skip(1) //跳過第1個 .limit(3) //最多返回3個 .sorted(String::compareTo) //排序 .peek(System.out::println) //打印結果 .collect(Collectors.toList()); //收集結果
//流的扁平化 //找出下面單詞所組成的字母 Arrays.asList("apple","tomato","peak").stream() .map(item->item.split("")) //返回 字符數組 .flatMap(Arrays::stream) //將 字符數組轉成流,再將流合併 .distinct() //去重 .collect(Collectors.toList()); //收集結果
//數值流 及 元素求和 // 有拆箱的操做 Optional<Integer> A = Stream.of(1, 2, 3, 4).reduce(Integer::sum); Integer B = Stream.of(1, 2, 3, 4).reduce(0, Integer::sum); LongStream.of(1, 2, 3, 4).boxed().reduce(Long::sum);//將原始類型轉成包裝類型 // 無拆箱操做 IntStream.of(1, 2, 3, 4).sum(); Stream.of(1, 2, 3, 4).mapToInt(x -> x).sum(); //將包裝類型轉原始類型 //數值範圍 LongStream.rangeClosed(1, 100).close(); // 1-100 包含100 IntStream.range(1,100).close(); //1-100 不包含100
//從 打開 data.txt 文件,並各行讀取內容。 try (Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())) { //在try()打開的文件,流會自動關閉,不用寫finally 去關閉流 lines.peek(System.out::println) .close(); } catch (IOException e) { //若是打開文件時出現出現異常則加以處理 }
//Collectors 使用 //收集 new ArrayList<Apple>().stream().collect(Collectors.toList()); //收集至list中 new ArrayList<Apple>().stream().collect(Collectors.toSet()); //收集至set中 new ArrayList<Apple>().stream().collect(Collectors.toCollection(HashSet::new));//自定義收集器 Map<String, Apple> map1 = new ArrayList<Apple>().stream() //收集至map中 .collect(Collectors.toMap(Apple::getName, Function.identity())); Map<String, Integer> map2 = new ArrayList<Apple>().stream() //收集至map中 .collect(Collectors.toMap(Apple::getName, Apple::getWeight)); //數值計算 Stream.of(1, 2, 3, 4).collect(Collectors.summingInt(x -> x)); //求和 Stream.of(1, 2, 3, 4).collect(Collectors.averagingInt(x -> x)); //平均值 Stream.of(1, 2, 3, 4).collect(Collectors.maxBy(Integer::compare)); //最大值 Stream.of(1, 2, 3, 4).collect(Collectors.minBy(Integer::compare)); //最小值 Stream.of(1, 2, 3, 4).collect(Collectors.counting()); //個數 IntSummaryStatistics stat = Stream.of(1, 2, 3, 4).collect(Collectors.summarizingInt(x -> x)); stat.getSum(); //求和 stat.getAverage(); //平均值 stat.getMax(); //最大值 stat.getMin(); //最小值 stat.getCount(); //個數 //字符串鏈接 Stream.of("a", "b", "c").collect(Collectors.joining()); //abc Stream.of("a", "b", "c").collect(Collectors.joining(","));//a,b,c Stream.of("a", "b", "c").collect(Collectors.joining(",", "[", "]"));//[a,b,c] //歸約 Integer sum = Stream.of(1, 2, 3, 4).collect(Collectors.reducing(0, Integer::sum)); //利用歸約來求和 Optional<Integer> sumOptional = Stream.of(1, 2, 3, 4).collect(Collectors.reducing(Integer::sum)); //利用歸約來求和 new ArrayList<Apple>().stream() .collect(Collectors.reducing(0, Apple::getWeight, Integer::sum)); //對蘋果的重量進行求和 //collectingAndThen 把收集器返回的結果轉換爲另外一種類型 //將找出最重的蘋果,返回 Apple對象,而不是 Optional<Application> Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingInt(Apple::getWeight)), Optional::get); // mapping 第一個參數表示變化,第二個參數表示收集 //獲取每一個蘋果的重量,並將其收集成set Collectors.mapping(Apple::getWeight, Collectors.toSet()); //分組 Map<Integer, List<Apple>> group1 = new ArrayList<Apple>().stream() //根據蘋果的重量進行分組 .collect(Collectors.groupingBy(Apple::getWeight)); Map<Integer, Map<String, List<Apple>>> group2 = new ArrayList<Apple>().stream() //根據蘋果的重量和名稱分組 .collect(Collectors.groupingBy(Apple::getWeight, Collectors.groupingBy(Apple::getName))); Map<String, Integer> group3 = new ArrayList<Apple>().stream() //根據蘋果的名稱分組,計算每組蘋果重量的和 .collect(Collectors.groupingBy(Apple::getName, Collectors.summingInt(Apple::getWeight))); Map<String, Optional<Apple>> group4 = new ArrayList<Apple>().stream() //根據蘋果的名稱分組,找出最重的蘋果 .collect(Collectors.groupingBy(Apple::getName, Collectors.maxBy(Comparator.comparingInt(Apple::getWeight)))); Map<String, Apple> group5 = new ArrayList<Apple>().stream() //根據蘋果的名稱分組,找出最重的蘋果 .collect(Collectors.groupingBy(Apple::getName, Collectors.collectingAndThen( Collectors.maxBy(Comparator.comparingInt(Apple::getWeight)), Optional::get))); Map<String, Set<Integer>> group6 = new ArrayList<Apple>().stream() //根據蘋果的名稱分組, 獲取每組蘋果的重量收集成set .collect(Collectors.groupingBy(Apple::getName, Collectors.mapping(Apple::getWeight, Collectors.toSet()))); //分區 Map<Boolean, List<Apple>> group7 = new ArrayList<Apple>().stream() //根據蘋果的重量分組,條件 weight>5 .collect(Collectors.partitioningBy(apple -> apple.getWeight() > 5)); this.diffItems.stream() //分組後再計算每組的數量 .collect(Collectors.groupingBy(TradeDiffItem::getDiffType, Collectors.counting())); Map<String, Apple> group9 = new ArrayList<Apple>().stream() //根據蘋果的名稱分組,找出每組中第一個元素 .collect(Collectors.groupingBy(Apple::getName, Collectors.collectingAndThen(Collectors.toList(), item-> item.get(0) ));