Stream流介绍 是一个来自数据源的元素源的元素队列并支持聚合操作
作用范围
数组 Arrays.stream()
单列集合Collection
双列集合Map
**Stream.of()**(直接构造流)
文件行流 (Files.lines()
)
函数生成流 (Stream.generate()
/ Stream.iterate()
)
中间操作
过滤 :filter
映射 :map
, flatMap
排序 :sorted
去重 :distinct
截断/跳过 :limit
, skip
终止操作 遍历 :forEach
聚合 :reduce
收集 :collect(Collectors.toList())
统计 :count
, max
, min
匹配 :anyMatch
, allMatch
, noneMatch
查找 :findFirst
, findAny
使用场景 练习 练习1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 import java.util.Arrays;import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.stream.Collectors;class Person { String name; int age; String city; public Person (String name, int age, String city) { this .name = name; this .age = age; this .city = city; } public String getName () { return name; } public int getAge () { return age; } public String getCity () { return city; } @Override public String toString () { return name + " (" + age + ", " + city + ")" ; } } public class StreamExe { public static void main (String[] args) { List<Person> people = Arrays.asList( new Person("Alice" , 23 , "Beijing" ), new Person("Bob" , 30 , "Shanghai" ), new Person("Charlie" , 28 , "Beijing" ), new Person("David" , 35 , "Guangzhou" ), new Person("Eve" , 40 , "Shanghai" ), new Person("Frank" , 18 , "Beijing" ) ); people.stream().filter(p -> "Beijing" .equals(p.getCity())).forEach(System.out::println); List<String> collect = people.stream().map(Person::getName).collect(Collectors.toList()); System.out.println(collect); people.stream().sorted(Comparator.comparingInt(Person::getAge)).map(Person::getName).forEach(System.out::println); people.stream().map(Person::getCity).distinct().forEach(System.out::println); System.out.println(people.stream().filter(p -> p.getAge() > 25 ).count()); System.out.println(people.stream().max(Comparator.comparingInt(Person::getAge))); System.out.println(people.stream().min(Comparator.comparingInt(Person::getAge))); System.out.println(people.stream().mapToInt(Person::getAge).average()); System.out.println(people.stream().collect(Collectors.averagingInt(Person::getAge))); Map<String, List<Person>> collect1 = people.stream().collect(Collectors.groupingBy(Person::getCity)); System.out.println(collect1); System.out.println(people.stream().map(Person::getName).collect(Collectors.joining("," ))); List<String> collect2 = people.stream().filter(p -> "Beijing" .equals(p.city) && p.age > 20 ).map(Person::getName).sorted().collect(Collectors.toList()); System.out.println(collect2); } }
在上面的练习中,从聚合计算平均数开始的使用方法有点不太熟悉。
练习2(进阶版)