JDK8新特性---stream流
项目上用到了stream流,找篇blog,转载一下,介绍下Stream流的用法。
1 流概述
流是 JDK8 新增的成员,允许以声明性方式处理数据集合,可以把 Stream 流看作是遍历数据集合的一个高级迭代器
使用流的好处: 代码以声明性方式书写:说明想要完成什么,而不是说明如何完 成一个操作 可以把几个基础操作连接起来,来表达复杂的数据处理的流水 线,同时保持代码清晰可读
流是什么?
从支持数据处理操作的源生成元素序列.数据源可以是集合,数组 或 IO 资源
从操作角度来看,流与集合是不同的. 流不存储数据值; 流的目的 是处理数据,它是关于算法与计算的. 如果把集合作为流的数据源,创建流时不会导致数据流动; 如果流 的终止操作需要值时,流会从集合中获取值; 流只使用一次 流中心思想是延迟计算,流直到需要时才计算值
流使用时一般包括三件事:
1) 一个数据源(如集合)来执行一个查询;
2) 一个中间操作链,形成一条流的流水线
3) 一个终端操作,执行流水线,生成结果
2 Stream流的几种获得方式
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 | public class Test01 { public static void main(String[] args) { //1 如何获得流,可以通过 Collection 集合,数据, 根据字面量获得流 // 1.1 通过 Collection 获得流 List<String> list = new ArrayList<>(); Collections.addAll(list, "aa" , "hello" , "jj" , "dd" , "mm" , "test" ); Stream<String> stream1 = list.stream(); System.out.println(stream1); stream1.forEach(System.out::println); // 1.2 根据数组获得流 String[]data = { "zhangsan" , "lisi" , "wangwu" }; Stream<String> stream2 = Arrays.stream(data); stream2.forEach(s -> System.out.print(s + " " )); System.out.println(); // 1.3 直接通过值获得流 Stream<String> stream3 = Stream.of( "1" , "2" , "3" , "4" ); stream3.forEach(s -> System.out.print(s + " " )); System.out.println(); // 1.4 无限流 Stream.iterate( 100 , x -> x + 3 ).limit( 10 ).forEach(s -> System.out.print(s + " " )); System.out.println(); } } |
3 Stream流的筛选操作
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 | public class Test01 { public static void main(String[] args) { List<String> list = new ArrayList<>(); Collections.addAll(list, "aa" , "aa" , "cc" , "d" , "bb" ); Stream<String> stream = list.stream(); //流的筛选与切片 //去重:distinct() stream.distinct().forEach(System.out::println); System.out.println( "-------------1-----------" ); //过滤filter(Predicate<? super T> predicate); 传递一个Predicate接口 // stream.filter(x -> x.length()>2).forEach(System.out::println); //java.lang.IllegalStateException: 流只能使用一次 list.stream().filter(x -> x.length() > 2 ).forEach(System.out::println); System.out.println( "-------------2-----------" ); //sorted()排序操作 Comparator<? super T> comparator 传递一个Comparator接口 list.stream().sorted(String::compareTo).forEach(System.out::println); System.out.println( "-------------3-----------" ); //limt()截断操作 list.stream().limit( 5 ).forEach(System.out::println); System.out.println( "--------------4----------" ); //skip()跳过 list.stream().skip( 3 ).forEach(System.out::println); System.out.println( "---------------5---------" ); } } |
4 Stream流的map映射
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class Test02 { public static void main(String[] args) { List<String> list = new ArrayList<>(); Collections.addAll(list, "aa" , "aa" , "bb" , "cc" , "d" , "eeeeee" ); //map(Function<? super T, ? extends R> mapper); 传递一个Function接口 //为每个元素应用toUpperCase()把小写转换为大写 list.stream().map(String::toUpperCase).forEach(System.out::println); //list每个每个元素的长度,然后拼接空格 2 2 2 2 1 6 list.stream().map(String::length).map(len->len + " " ).forEach(System.out::println); System.out.println( "----------2-------" ); //转换为数值流 List<Integer> integerList= Arrays.asList( 54 , 1 , 78 , 90 , 345 ); IntStream intStream = integerList.stream().mapToInt(x->x); intStream.forEach(x->System.out.print(x+ " " )); } } |
5 Stream流的查找与匹配
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 | public class Test03 { public static void main(String[] args) { List<String> list = new ArrayList<>(); Collections.addAll(list, "aa" , "aa" , "bb" , "cc" , "d" , "eeeeee" , "sssssss" ); //allMatch()判断流中所有的元素是否都匹配给定的谓词 System.out.println(list.stream().allMatch(s -> s.length() > 3 )); //false //anyMatch()判断流中是否有某个元素可以匹配指定的谓词 System.out.println(list.stream().anyMatch(s -> s.equals( "wkcto" ))); //true //noneMathc()判断流中的元素是否都没有匹配指定谓词的 System.out.println(list.stream().noneMatch(s -> s.equals( "jj" ))); //false //findAny()和findFirst()的返回值类型均为Optional<T> //查找任意一个 System.out.println(list.stream().filter(s -> s.length() > 5 ).findAny().get()); //查找第一个 try { System.out.println(list.stream().filter(s -> s.length() > 20 ).findFirst().get()); } catch (Exception e) { e.printStackTrace(); } //查找第一个,如果不加orElse 会输出Optional.empty System.out.println(list.stream().filter(s -> s.length() > 20 ).findFirst().orElse( "不存在" )); } } |
6 Stream流的reduce规约
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 | public class Test04 { public static void main(String[] args) { List<String> list = new ArrayList<>(); Collections.addAll(list, "aa" , "aa" , "bb" , "cc" , "d" , "eeeeee" , "sssssss" ); //1 forEach 遍历 list.stream().forEach(System.out::println); //2 cout 统计 System.out.println(list.stream().filter(x -> x.length() > 2 ).count()); //3 reduce 归纳合并 //传递的是BinaryOperator<T> accumulator 接口 Optional<String> reduce = list.stream().reduce((s1, s2) -> s1 + "--" + s2); System.out.println(reduce.get()); //传递Consumer<? super T> consumer 接口 reduce.ifPresent(System.out::println); //4数值操作 List<Integer> list2 = Arrays.asList( 6 , 21 , 87 , 34 , 1 , 78 , 54 ); //5求和,指定初始值 //reduce(T identity, BinaryOperator<T> accumulator); System.out.println(list2.stream().reduce( 0 , Integer::sum)); //求和,没有初始值 //Optional<T> reduce(BinaryOperator<T> accumulator); System.out.println(list2.stream().reduce((x, y) -> x + y).orElse( 0 )); //6最值 //Optional<T> reduce(BinaryOperator<T> accumulator); System.out.println(list2.stream().reduce(Math::max).get()); System.out.println(list2.stream().reduce(Math::min).get()); } |
7 Stream流映射到数值流
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 | public class Test05 { public static void main(String[] args) { List<Integer> list2 = Arrays.asList( 6 , 21 , 87 , 34 , 1 , 78 , 54 ); //求和 IntStream mapToInt(ToIntFunction<? super T> mapper); System.out.println(list2.stream().mapToInt(x->x).sum() ); //最大值 OptionalInt max(); //public int getAsInt() { // if (!isPresent) { // throw new NoSuchElementException("No value present"); // } // return value; // } System.out.println(list2.stream().mapToInt(x->x).max().getAsInt() ); //最小值 OptionalInt min(); //public int orElse(int other) { // return isPresent ? value : other; //} System.out.println(list2.stream().mapToInt(x->x).min().orElse( 0 ) ); //平均值 //DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper); //OptionalDouble average(); System.out.println(list2.stream().mapToDouble(x->x).average().getAsDouble()); //求最大值 System.out.println(list2.stream().max(Integer::compareTo).get()); //求最小值 list2.stream().min(Integer::compareTo).ifPresent(System.out::println); } } |
8 Stream流的collect规约
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class Test06 { public static void main(String[] args) { List<String> list = new ArrayList<>(); Collections.addAll(list, "ss" , "aa" , "hello" , "jj" , "hello" , "xx" , "good" ); //把 stream 流转换为集合 Set<String> stringSet = list.stream().collect(Collectors.toSet()); System.out.println( stringSet ); //把 Stream 流转换为数组 Object[] objects = list.stream().toArray(); System.out.println( Arrays.toString(objects)); String[] toArray = list.stream().toArray(String[]:: new ); System.out.println(Arrays.toString(toArray)); //Stream 流转换为字符串 String collect = list.stream().collect(Collectors.joining( "," )); System.out.println(collect); } } |
————————————————
版权声明:本文为CSDN博主「ChengZi~」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38339124/article/details/93423360
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)