Stream
是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
“集合讲的是数据,流讲的是计算! ”
注意:
取出所有大于18岁人的姓名,按字典排序,并输出到控制台
public class StreamDemo { private static List<Person> persons = Arrays.asList( new Person("CJK", 19, "女"), new Person("BODUO", 20, "女"), new Person("JZ", 21, "女"), new Person("anglebabby", 18, "女"), new Person("huangxiaoming", 5, "男"), new Person("ROY", 18, "男") ); public static void main(String[] args) throws IOException { persons.stream().filter(x -> x.getAge() >= 18).map(Person::getName).sorted().forEach(System.out::println); } } 复制代码
BODUO CJK JZ ROY anglebabby 复制代码
Stream
Collection
提供了两个方法 stream()
与 parallelStream()
Arrays
中的 stream()
获取一个数组流 Stream
类中静态方法 of()
public void test1(){ //1. Collection 提供了两个方法 stream() 与 parallelStream() List<String> list = new ArrayList<>(); Stream<String> stream = list.stream(); //获取一个顺序流 Stream<String> parallelStream = list.parallelStream(); //获取一个并行流 //2. 通过 Arrays 中的 stream() 获取一个数组流 Integer[] nums = new Integer[10]; Stream<Integer> stream1 = Arrays.stream(nums); //3. 通过 Stream 类中静态方法 of() Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6); //4. 创建无限流 //迭代 Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10); stream3.forEach(System.out::println); //生成 Stream<Double> stream4 = Stream.generate(Math::random).limit(2); stream4.forEach(System.out::println); } 复制代码
问题:
下面创建流(Stream)的方式哪些是正确的(多选) => C,D,E,F
A. Steam.newInstanceOf()
B. Collection.of()
C. Collection.stream() 或Collection.parallelStream()
D.Stream.of()
E.Stream.generate() 或 Stream.iterate()
F.Arrays.stream()
问题:
Integer[] ary = {1,2,3,4,5,6,7,8,9,10}
,取出中间的第三到第五个元素 List<Integer> collect = Arrays.stream(ary).skip(2).limit(3).collect(Collectors.toList()); 复制代码
Integer[] ary = {1,2,2,3,4,5,6,6,7,8,8,9,10},
取出里面的偶数,并去除重复 List<Integer> list = Arrays.stream(ary).filter(x -> x % 2 == 0).distinct().collect(Collectors.toList()); Set<Integer> integerSet = Arrays.stream(ary).filter(x -> x % 2 == 0).collect(Collectors.toSet()); 复制代码
(1,2,3,4,5……12)
Integer ary = {{3,8,4,7,5}, {9,1,6,2}, {0,10,12,11} }; Arrays.stream(ary).flatMap(item->Arrays.stream(item)).sorted().forEach(System.out::println); 复制代码
终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如: List
、 Integer
,甚至是 void
。
查找与匹配
接口 | 说明 |
---|---|
allMatch(Predicate p) | 检查是否匹配所有元素 |
anyMatch(Predicate p) | 检查是否至少匹配一个元素 |
noneMatch(Predicate p) | 检查是否没有匹配所有元素 |
findFirst() | 返回第一个元素 |
findAny() | 返回当前流中的任意元素 |
count() | 返回流中元素总数 |
max(Comparator c) | 返回流中最大值 |
min(Comparator c) | 返回流中最小值 |
forEach(Consumer c) | 迭代 |
问题:
Integer[] ary = {1,2,3,4,5,6,7,8,9,10}
boolean result1 = Arrays.stream(ary).allMatch(x -> x < 10); System.out.println(result1); 复制代码
boolean result2 = Arrays.stream(ary).anyMatch(x -> x < 2); System.out.println(result2); 复制代码
boolean result3 = Arrays.stream(ary).noneMatch(x -> x > 2); System.out.println(result3); 复制代码
Optional<Integer> first = Arrays.stream(ary).findFirst(); System.out.println(first.get()); 复制代码
long count = Arrays.stream(ary).count(); System.out.println(count); 复制代码
Optional<Integer> max = Arrays.stream(ary).max(Integer::compareTo); System.out.println(max.get()); 复制代码
Optional<Integer> min = Arrays.stream(ary).min(Integer::compareTo); System.out.println(min.get()); 复制代码
Arrays.stream(ary).filter(x -> x % 2 == 0).forEach(System.out::println); 复制代码
reduce(T iden, BinaryOperator b)
可以将流中元素反复结合起来,得到一个值。返回 T
reduce(BinaryOperator b)
可以将流中元素反复结合起来,得到一个值。返回 Optional<T>
问题:求所有人员学生的总分
Integer all = persons.stream().map(Person::getScore).reduce((integer, integer2) -> integer + integer2).get() 复制代码
collect(Collector c)
将流转换为其他形式。接收一个 Collector
接口的实现,用于给 Stream
中元素做汇总的方法
Collector
接口中方法的实现决定了如何对流执行收集操作(如收集到 List
、 Set
、 Map
)。
Collectors
实用类提供了很多静态方法,可以方便地创建常见收集器实例
List<Person> emps= list.stream().collect(Collectors.toList()); 复制代码
Set<Person> emps= list.stream().collect(Collectors.toSet()); 复制代码
Collection<Person> emps=list.stream().collect(Collectors.toCollection(ArrayList::new)); 复制代码
long count = list.stream().collect(Collectors.counting()); 复制代码
int total=list.stream().collect(Collectors.summingInt(Person::getAge)); 复制代码
double avg= list.stream().collect(Collectors.averagingInt(Person::getAge)); 复制代码
Int SummaryStatisticsiss= list.stream().collect(Collectors.summarizingInt(Person::getAge)); 复制代码
String str= list.stream().map(Person::getName).collect(Collectors.joining()); 复制代码
Optional<Person> max= list.stream().collect(Collectors.maxBy(comparingInt(Person::getSalary))); 复制代码
Optional<Person> min = list.stream().collect(Collectors.minBy(comparingInt(Person::getSalary))); 复制代码
int total=list.stream().collect(Collectors.reducing(0, Person::getSalar, Integer::sum)); 复制代码
int how= list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), List::size)); 复制代码
Map<Person.Status,List<Person>> map= list.stream().collect(Collectors.groupingBy(Person::getStatus)); partitioningBy Map<Boolean, List<T>> 根据true或false进行分区 Map<Boolean,List<Person>>vd= list.stream().collect(Collectors.partitioningBy(Person::getManage)); 复制代码
Integer[] ary = {1,2,3,4,5,6,7,8,9,10}
Optional<Integer> collect = Arrays.stream(ary).collect(Collectors.maxBy(Comparator.comparing(x -> x))); System.out.println(collect.get()); 复制代码
IntSummaryStatistics collect1 = Arrays.stream(ary).collect(Collectors.summarizingInt(x -> x)); System.out.println(collect1.getAverage()); 复制代码
String collect2 = Arrays.stream(ary).map(x -> x.toString()).collect(Collectors.joining(":")); System.out.println(collect2); 复制代码
int total=Arrays.stream(ary).collect(Collectors.reducing(0, x->x, Integer::sum)); System.out.println(total); 复制代码
Long collect3 = Arrays.stream(ary).collect(Collectors.counting()); System.out.println(collect3); 复制代码
List<String> collect2 = persons.stream().map(Person::getName).collect(Collectors.toList()); 复制代码
IntSummaryStatistics collect = persons.stream().collect(Collectors.summarizingInt(Person::getScore)); System.out.println(collect); 复制代码
Map<Boolean, List<Person>> collect1 = persons.stream().collect(Collectors.partitioningBy(person -> person.getScore() >= 60)); System.out.println(collect1); 复制代码
public static void main(String[] args) throws IOException { InputStream resourceAsStream = Person.class.getClassLoader().getResourceAsStream("aa.txt"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resourceAsStream)); bufferedReader.lines().flatMap(x->Stream.of(x.split(" "))).sorted().collect(Collectors.groupingBy(String::toString)).forEach((a,b)-> System.out.println(a+":"+b.size())); bufferedReader.close(); } 复制代码