一、概述
在Java8中,使用Stream配合同版本出現的Lambda,給我們操作集合(Collection)提供了極大的便利。
Stream將要處理的元素集合看作一種流,在流的過程中,借助Stream API對流中的元素進行操作,比如:篩選、排序、聚合等。
二、Stream創建
Stream流可以通過集合、數組來創建。
List<String> list = Arrays.asList("a", "b", "c"); Stream<String> stream = list.stream();
三、使用
3.1、遍歷、匹配
forEach
List<Integer> list = Arrays.asList(10, 5, 8, 20, 32, 6); // 遍歷輸入每一個元素 list.stream().forEach(item -> { System.out.println(item); }); // 10 // 5 // 8 // 20 // 32 // 6
find
List<Integer> list = Arrays.asList(10, 5, 8, 20, 32, 6); // 獲取第一個值 Integer integer = list.stream().findFirst().get(); // 10
match
List<Integer> list = Arrays.asList(10, 5, 8, 20, 32, 6); // list集合中是否有大於30的數 boolean b = list.stream().anyMatch(i -> i > 30); // true // list集合中是否有大於50的數 boolean b2 = list.stream().anyMatch(i -> i > 50); // false
3.2、篩選
filter
List<Integer> list = Arrays.asList(10, 5, 8, 20, 7, 6); // 打印list集合中所有的奇數 list.stream().filter(i -> i % 2 != 0).forEach(System.out::println); // 5 // 7
3.3、聚合
max、min
List<String> list = Arrays.asList("jack", "tom", "alice"); // 取出list中最長的字符串 String max = list.stream().max(Comparator.comparing(String::length)).get(); // alice String min = list.stream().min(Comparator.comparing(String::length)).get(); // tom
count
List<Integer> list = Arrays.asList(10, 5, 8, 20, 7, 6); // 獲取list集合中偶數的個數 long count = list.stream().filter(i -> i % 2 == 0).count(); // 4
3.4、映射
map
List<String> list = Arrays.asList("jack", "tom", "alice"); // 名字全轉大寫 List<String> list2 = list.stream().map(String::toUpperCase).collect(Collectors.toList()); // [JACK, TOM, ALICE]
---
List<Integer> list = Arrays.asList(10, 5, 8, 20, 7, 6); // 每個都加100 List<Integer> list2 = list.stream().map(i -> i + 100).collect(Collectors.toList()); // [110, 105, 108, 120, 107, 106]
---
List<Student> list = Arrays.asList( new Student(1, "jack"), new Student(2, "alice"), new Student(3, "tom") ); // 將對象列表轉為字符串列表 List<String> names = list.stream().map(student -> student.getName()).collect(Collectors.toList()); // [jack, alice, tom]
3.5、歸約
reduce
List<Integer> list = Arrays.asList(10, 5, 8, 20, 7, 6); // 求集合元素之和 Integer num = list.stream().reduce(Integer::sum).get(); // 56
3.6、收集(collect)
toList
List<Integer> list = Arrays.asList(10, 5, 8, 20, 7, 6); // 找出集合中的偶數,並返回新的集合 List<Integer> newList = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList()); // [10, 8, 20, 6]
toSet
List<Integer> list = Arrays.asList(10, 5, 8, 20, 7, 6); // 找出集合中的偶數,並返回新的集合 Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet()); // [20, 6, 8, 10]
參考:Java8 Stream:2萬字20個實例,玩轉集合的篩選、歸約、分組、聚合