当前位置: 首页 > news >正文

JAVA学习-Stream

Stream

        Stream也叫Stream流,是Jdk8开始新增的一套API (java.util.stream.*),可以用于操作集合或者数 组的数据。

        优势: Stream流大量的结合了Lambda的语法风格来编程,提供了一种更加强大,更加简单的方式 操作集合或者数组中的数据,代码更简洁,可读性更好。

案例:体验Strema流

import java.util.*;
import java.util.stream.Collectors;/*目标 : 初步体验Stream流的方便与快捷需求 : 把集合中所有以“张”开头,且是3个字的元素存储到一个新的集合。*/
public class StreamTest1 {public static void main(String[] args) {List<String> names = new ArrayList<>();Collections.addAll(names, "张三丰","张无忌","周芷若","赵敏","张强");ArrayList<String> newNames = new ArrayList<>();for (int i = 0; i < names.size(); i++) {String name = names.get(i);if (name.startsWith("张")&&name.length() == 3){newNames.add(name);}}System.out.println(newNames);//stream流List<String> list = names.stream().filter(name1 ->{return name1.startsWith("张") && name1.length() == 3;}).collect(Collectors.toList());System.out.println(list);}
}

 运行结果:

[张三丰, 张无忌]
[张三丰, 张无忌]Process finished with exit code 0

Stream流处理数据的步骤:

        先得到集合或者数组的Stream流。

        然后调用Stream流的方法对数据进行处理。

        获取处理的结果。

获取 集合 的Stream流使用下面方法:

default Stream<E> stream​() 获取当前集合对象的Stream流 

获取 数组 的Stream流使用下面方法:

public static <T> Stream<T> stream(T[] array) 获取当前数组的Stream流 public static<T> Stream<T> of(T... values)  获取当前接收数据的Stream流

示例:各种数组集合获取Stream演示:

import java.util.*;
import java.util.stream.Stream;/*目标:掌握Stream流的创建。1 单列集合获取Stream流2 双列集合获取Stream流3 数组获取Stream流4 同一种类型多个数据获取Stream流*/
public class StreamTest2 {public static void main(String[] args) {// 1、如何获取List集合的Stream流?List<String> names = new ArrayList<>();Collections.addAll(names, "张三丰","张无忌","周芷若","赵敏","张强");names.stream().forEach(s -> {System.out.println(s);});//        2 双列集合获取Stream流System.out.println("------------------------");HashMap<String, String> map = new HashMap<>();map.put("1","1");map.put("2","3");map.put("3","3");// 获取双列集合的Set集合Set<Map.Entry<String, String>> entrySet = map.entrySet();// 获取双列集合的Stream流entrySet.stream().forEach(st ->{System.out.println(st.getKey()+st.getValue());} );//        3 数组获取Stream流System.out.println("------------------------");String[] arr={"4","5","6"};// 获取数组的Stream流Arrays.stream(arr).forEach(s -> {System.out.println(s);});//        4 同一种类型多个数据获取Stream流System.out.println("------------------------");// 获取Stream流Stream.of("7","8","9").forEach(s -> {System.out.println(s);});}
}

运行结果:

张三丰
张无忌
周芷若
赵敏
张强
------------------------
11
23
33
------------------------
4
5
6
------------------------
7
8
9Process finished with exit code 0

Stream流常见的中间方法:

Stream<T> filter(Predicate<? super T> predicate) 
用于对流中的数据进行过滤Stream<T> sorted() 
对元素进行升序排序 Stream<T> sorted(Comparator<? super T> comparator) 
按照指定规则排序Stream<T> limit​(long maxSize) 
获取前几个元素Stream<T> skip​(long n) 
跳过前几个元素 Stream<T> distinct​() 
去除流中重复的元素<R> Stream<R> map​( Function<? super T,​? extends R> mapper) 
对元素进行加工,并返回对应的新流static <T> Stream<T> concat​(Stream a, Stream b)  
合并a和b两个流为一个流

演示代码:

import java.util.*;
import java.util.stream.Stream;/*目标:掌握Stream流提供的常见中间方法。Stream<T> filter(Predicate<? super T> predicate)	用于对流中的数据进行过滤。Stream<T> sorted()	对元素进行升序排序Stream<T> sorted(Comparator<? super T> comparator)	按照指定规则排序Stream<T> limit(long maxSize)	获取前几个元素Stream<T> skip(long n)	跳过前几个元素Stream<T> distinct()	去除流中重复的元素。<R> Stream<R> map(Function<T , R> mapper)	对元素进行加工,并返回对应的新流static <T> Stream<T> concat(Stream a, Stream b)	合并a和b两个流为一个流*/
public class StreamTest3 {public static void main(String[] args) {List<Double> scores = new ArrayList<>();Collections.addAll(scores, 88.5, 100.0, 60.0, 99.0, 9.5, 99.6, 25.0);// 需求1:找出成绩大于等于60分的数据,并升序后,再输出。scores.stream().filter(s->{return s>=60;}).sorted().forEach(s-> System.out.print(s+" "));System.out.println(" ");System.out.println("---------------");List<Student> students = new ArrayList<>();Student s1 = new Student("蜘蛛精", 26, 172.5);Student s2 = new Student("蜘蛛精", 26, 172.5);Student s3 = new Student("紫霞", 23, 167.6);Student s4 = new Student("白晶晶", 25, 169.0);Student s5 = new Student("牛魔王", 35, 183.3);Student s6 = new Student("牛夫人", 34, 168.5);Collections.addAll(students, s1, s2, s3, s4, s5, s6);// 需求2:找出年龄大于等于23,且年龄小于等于30岁的学生,并按照年龄降序输出.students.stream().filter(student -> {return student.getAge()>=23&&student.getAge()<=30;}).sorted(new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {return o2.getAge()-o1.getAge();}}).forEach(student -> System.out.println(student));System.out.println("---------------");// 需求3:取出身高最高的前3名学生,并输出。students.stream().sorted(new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {return Double.compare(o2.getHeight(), o1.getHeight());}}).limit(3).forEach(student -> System.out.println(student));System.out.println("---------------");// 需求4:取出身高倒数的2名学生,并输出。students.stream().sorted(new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {return Double.compare(o2.getHeight(), o1.getHeight());}}).skip(students.size()-2).forEach(student -> System.out.println(student));System.out.println("---------------");students.stream().sorted(new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {return Double.compare(o1.getHeight(), o2.getHeight());}}).limit(2).forEach(student -> {System.out.println(student);});// 需求5:找出身高超过168的学生叫什么名字,要求去除重复的名字,再输出。System.out.println("---------------");students.stream().filter(s-> s.getHeight()>168).map(student -> student.getName()).distinct().forEach(s -> System.out.print(s+" "));System.out.println(" ");System.out.println("---------------");Stream.concat(scores.stream(),scores.stream()).forEach(s-> System.out.print(s+" "));}
}

运行结果:

60.0 88.5 99.0 99.6 100.0  
---------------
Student{name='蜘蛛精', age=26, height=172.5}
Student{name='蜘蛛精', age=26, height=172.5}
Student{name='白晶晶', age=25, height=169.0}
Student{name='紫霞', age=23, height=167.6}
---------------
Student{name='牛魔王', age=35, height=183.3}
Student{name='蜘蛛精', age=26, height=172.5}
Student{name='蜘蛛精', age=26, height=172.5}
---------------
Student{name='牛夫人', age=34, height=168.5}
Student{name='紫霞', age=23, height=167.6}
---------------
Student{name='紫霞', age=23, height=167.6}
Student{name='牛夫人', age=34, height=168.5}
---------------
蜘蛛精 白晶晶 牛魔王 牛夫人  
---------------
88.5 100.0 60.0 99.0 9.5 99.6 25.0 88.5 100.0 60.0 99.0 9.5 99.6 25.0 
Process finished with exit code 0

Stream流常见的终结方法:

void forEach​(Consumer action) 
对此流运算后的元素执行遍历 long count​() 
统计此流运算后的元素个数 Optional<T> max​(Comparator<? super T> comparator) 
获取此流运算后的最大值元素Optional<T> min​( Comparator<? super T> comparator) 
获取此流运算后的最小值元素//收集Stream流:就是把Stream流操作后的结果转回到集合或者数组中去返回。R collect​(Collector collector) 
把流处理后的结果收集到一个指定的集合中去 Object[] toArray() 
把流处理后的结果收集到一个数组中去

Collectors工具类提供了具体的收集方式:

public static <T> Collector toList​() 
把元素收集到List集合中 public static <T> Collector toSet​() 
把元素收集到Set集合中 public static  Collector toMap​(Function keyMapper , Function valueMapper) 
把元素收集到Map集合中 

演示代码:

import java.util.*;
import java.util.stream.Collectors;/*目标:Stream流的终结方法void forEach(Consumer action)	对此流运算后的元素执行遍历long count()	统计此流运算后的元素个数Optional<T> max(Comparator<? super T> comparator)	获取此流运算后的最大值元素Optional<T> min(Comparator<? super T> comparator)	获取此流运算后的最小值元素*/
public class StreamTest4 {public static void main(String[] args) {List<Student> students = new ArrayList<>();Student s1 = new Student("蜘蛛精", 26, 172.5);Student s2 = new Student("蜘蛛精", 26, 172.5);Student s3 = new Student("紫霞", 23, 167.6);Student s4 = new Student("白晶晶", 25, 169.0);Student s5 = new Student("牛魔王", 35, 183.3);Student s6 = new Student("牛夫人", 34, 168.5);Collections.addAll(students, s1, s2, s3, s4, s5, s6);// 需求1:请计算出身高超过168的学生有几人。System.out.println(students.stream().filter(student -> student.getHeight() > 168).count());// 需求2:请找出身高最高的学生对象,并输出。System.out.println(students.stream().max(new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {return Double.compare(o1.getHeight(), o2.getHeight());}}));// 需求3:请找出身高最矮的学生对象,并输出。System.out.println(students.stream().min(new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {return Double.compare(o1.getHeight(), o2.getHeight());}}));// 需求4:请找出身高超过170的学生对象,并放到一个新集合中去返回。List<Student> list = students.stream().filter(student -> student.getHeight() > 170).collect(Collectors.toList());System.out.println(list);Set<Student> set = students.stream().filter(student -> student.getHeight() > 170).collect(Collectors.toSet());System.out.println(set);// 需求5:请找出身高超过170的学生对象,并把学生对象的名字和身高,存入到一个Map集合返回。Map<String, Double> map = students.stream().filter(student -> student.getHeight() > 170).distinct().collect(Collectors.toMap((k) -> {return k.getName();},(v) -> {return v.getHeight();}));System.out.println(map);}
}

运行结果:

5
Optional[Student{name='牛魔王', age=35, height=183.3}]
Optional[Student{name='紫霞', age=23, height=167.6}]
[Student{name='蜘蛛精', age=26, height=172.5}, Student{name='蜘蛛精', age=26, height=172.5}, Student{name='牛魔王', age=35, height=183.3}]
[Student{name='牛魔王', age=35, height=183.3}, Student{name='蜘蛛精', age=26, height=172.5}]
{蜘蛛精=172.5, 牛魔王=183.3}Process finished with exit code 0

#学无止尽    #记录并分享我的学习日常

相关文章:

  • Spring IoC与DI详解:从Bean概念到手写实现
  • Spring Batch 专题系列(四):配置与调度 Spring Batch 作业
  • 分库分表-除了hash分片还有别的吗?
  • 算法思想之分治-快排
  • Java基础 4.15
  • PCL八叉树聚类
  • Python基础语法2
  • 游戏代码编辑
  • 凸优化第2讲:凸优化建模
  • 一篇文章快速上手linux系统中存储多路径multipath的配置
  • MCP、RAG与Agent:下一代智能系统的协同架构设计
  • Cribl 中数据脱敏mask 的实验
  • 【HDFS】BlockPlacementPolicyRackFaultTolerant#getMaxNode方法的功能及具体实例
  • BufferedReader 终极解析与记忆指南
  • 使用python求函数极限
  • Java实现选择排序算法
  • 盛水最多的容器问题详解:双指针法与暴力法的对比与实现
  • vcast工具env环境问题二:<command-line>: error: stray ‘\’ in program
  • 深入解析 sklearn 中的 LabelEncoder:功能、使用场景与注意事项
  • 三、The C in C++
  • 鲁比奥称“美或退出俄乌谈判”,欧洲官员:为了施压乌克兰
  • 网信部门持续整治利用未成年人形象不当牟利问题
  • 李强签署国务院令,公布《国务院关于修改〈快递暂行条例〉的决定》
  • 释新闻|加州诉特朗普政府:美国最大经济体为何打响关税阻击战?
  • G20召开发展工作组第二次会议,中方就美“对等关税”阐明立场
  • 首季中国经济观察:一季度社融增量超15万亿元传递积极信号