java8 Stream流

java8 stream流

理论:
stream是用于对集合迭代器的增强,能够完成高效聚合操作(过滤,排序,统计分组)或大批量数据操作
流的操作特性
1,stream不存储数据
2,stream 不改变数据源
3,stream不可重复使用
流的操作类型
中间操作:
调用中间操作方法会返回一个新的流,通过连续执行多个操作就组成了Stream中的执行管道,需要注意的是这些管道被添加后并不会真正执行,只有等到终止操作后才会执行。
无状态:处理的元素不受之前元素的影响
unordered()
filter() 返回结果生成新的流中只包含满足筛选条件的数据
map() 接收一个函数作为参数,将流中的每个元素通过此函数映射为新的元素,病作为新流中对应的元素

Stream<Integer> stream = Stream.of(1, 2, 3);
stream.map(a->a * a).forEach(System.out::print); // 149

mapToInt()
mapToLong()
mapToDouble()
flatMap() 将流中的每个元素都放到一个流中,最后将所有流合并成一个新流,所有流对象的元素都合并到新生成的流中返回

List<Integer> num1 = Arrays.asList(1, 2, 3);
List<Integer> num2 = Arrays.asList(4, 5, 6);
List<Integer> num3 = Arrays.asList(7, 8, 9);
List<List<Integer>> lists = Arrays.asList(num1, num2, num3);
Stream<Integer> outputStream = lists.stream().flatMap(l -> l.stream());
List<Integer> flatMapResult = outputStream.sorted().collect(Collectors.toList());
System.out.println(flatMapResult);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

flatMapToInt()
flatMapToLong()
flatMapToDouble()
peek() 对流中每个元素执行操作,并返回一个新的流,返回的流还是原来流中的元素,与map类似

有状态:该操作只有拿到所有元素之后才能继续下去
distinct() 数据去重
sorted() 自然排序,流中的元素实现Comparable接口,默认从小到大排序
sorted(Comparator com) 定制排序,自定义Comparator排序器

List<String> list = Arrays.asList("aa", "ff", "dd");
//String 类自身已实现Compareable接口
list.stream().sorted().forEach(System.out::println);// aa dd ff
 
Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
Student s3 = new Student("aa", 30);
Student s4 = new Student("dd", 40);
List<Student> studentList = Arrays.asList(s1, s2, s3, s4);
 
//自定义排序:先按姓名升序,姓名相同则按年龄升序
studentList.stream().sorted(
        (o1, o2) -> {
            if (o1.getName().equals(o2.getName())) {
                return o1.getAge() - o2.getAge();
            } else {
                return o1.getName().compareTo(o2.getName());
            }
        }
).forEach(System.out::println);

limit(n) 返回指定数量的元素流,返回的是stream里面前面的n个元素
skip(n) 将前几个元素跳过(取出)再返回一个流,如果流中的元素小于或者等于n,就会返回一个空的流

终止操作:
在调用该方法后,将执行之前的所有中间操作,获取返回结果,病结束对流的使用
非短路操作:指必须处理所有元素才能得到最终结果
forEach() 内部迭代,串行按照顺序
forEachOrdered() 在并行中:forEachOrdered() 严格按照原来顺序取数,foreach是随机排列

toArray() 流转数组
reduce() 可以将流中元素反复结合起来,得到一个值

List<Integer> list = Arrays.asList(1,2,3,4);
// reduce()方法中第一个参数是起始值,第二个参数Lambda表达式中第一个参数x就是起始值,lambda表达式第二个参数y就是集合中的每个值
// 遍历集合中每个参数作为y,然后进行计算(x+y) 得到结果作为x,最后将所有结果相加,得到sum
Integer sum = list.stream().reduce(0, (x, y) -> x + y);
System.out.println(sum); // 10


Integer sum = list.stream().reduce((x, y) -> x + y).get();
System.out.println(sum); // 10

collect() 将流转为其他形式,接收一个Collector接口的实现,用户给strem中元素做汇总的方法
max() 返回流中最大值
min() 但会流中最小值
count() 返回流中总数
短路操作:指遇到某些符合条件的元素就可以得到最终结果,如A||B,只要A为true,则无需判断B的结果
anyMatch()
allMatch() 检查是和否匹配所有元素
noneMatch() 检查是否没有匹配所有元素
findFirst() 返回第一个元素
findAny() 返回当前流中的任意元素
Collectors.toCollection() 自定义转换类型 允许对集合再做一次操作

List<String> custListResult = list.stream().collect(Collectors.toCollection(LinkedList::new));
System.out.println(custListResult.getClass()); // class java.util.LinkedList

Collectors.collectingAndThen()

List<String> collectAndThenResult = list.stream()                .collect(Collectors.collectingAndThen(Collectors.toList(), l -> {return new ArrayList<>(l);}));
System.out.println(collectAndThenResult);	// [A, B, C, D]

Collectors.joining() :joining用来连接stream中的元素

String joinResult = list.stream().collect(Collectors.joining());
System.out.println(joinResult);	// ABCD
String joinResult1 = list.stream().collect(Collectors.joining(" "));
System.out.println(joinResult1);// A B C D
String joinResult2 = list.stream().collect(Collectors.joining(" ", "E","F"));
System.out.println(joinResult2);// EA B C D

Collectors.counting() counting主要用来统计stream中元素个数
Collectors.summarizingDouble/Long/Int() summarzingDouble/Long/Int为stream中的元素生成了统计信息,返回的结果是一个统计类

IntSummaryStatistics intResult = list.stream()
                .collect(Collectors.summarizingInt(String::length));
System.out.println(intResult);	// IntSummaryStatistics{count=4, sum=4, min=1, average=1.000000, max=1}

Collectors.averagingDouble/Long/Int()
averagingDouble/Long/Int()对stream中的元素做平均

Collectors.summingDouble/Long/Int()
summingDouble/Long/Int() 对stream中的元素做sum操作

Collectors.maxBy()/minBy()
maxBy() /minBy()根据提供的Comparator,返回stream中的最大或者最小值

Optional<String> maxByResult = list.stream().collect(Collectors.maxBy(Comparator.naturalOrder()));
System.out.println(maxByResult);	// Optional[D]

Collectors.groupingBy()
GroupingBy根据某些属性进行分组,并返回一个Map

Map<Integer, Set<String>> groupByResult = list.stream()
                .collect(Collectors.groupingBy(String::length, Collectors.toSet()));
System.out.println(groupByResult);	// {1=[A, B, C, D]}

Collectors.partitioningBy()
PartitioningBy是一个特别的groupingBy,PartitioningBy返回一个Map,这个Map是以boolean值为key,从而将stream分成两部分,一部分是匹配PartitioningBy条件的,一部分是不满足条件的

Map<Boolean, List<String>> partitionResult = list.stream()
                .collect(Collectors.partitioningBy(s -> s.length() > 3));
System.out.println(partitionResult); // {false=[A, B, C, D], true=[]}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值