Java8的Stream流的学习

news/2024/11/30 1:38:53/

一.概念理解

Stream可以由数组或集合创建,对流的操作分为两种:

  1. 中间操作,每次返回一个新的流,可以有多个。
  2. 终端操作,每个流只能进行一次终端操作,终端操作结束后流无法再次使用。终端操作会产生一个新的集合或值。

二、Stream的创建

public class StreamDemo {public static void main(String[] args) {// 集合List<Integer> list = Arrays.asList(1, 2, 3);// 集合创建一个顺序流Stream<Integer> stream = list.stream();// 集合创建一个并行流Stream<Integer> parallelStream = list.parallelStream();// 数组int[] array = {1, 3, 5, 6, 8};// 数组创建流方式IntStream intStream = Arrays.stream(array);}
}

stream和parallelStream的简单区分: stream是顺序流,由主线程按顺序对流执行操作,而parallelStream是并行流,内部以多线程并行执行的方式对流进行操作,但前提是流中的数据处理没有顺序要求

三.方法学习

1、遍历/匹配(foreach/find/match)

import java.util.*;/*** @author qinxun* @date 2023-06-02* @Descripion: 职工测试类*/
public class EmployeeDemo {public static void main(String[] args) {List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);// foreachlist.forEach(System.out::println);System.out.println("----------");//findOptional<Integer> firstData = list.stream().findFirst();System.out.println(firstData.get());System.out.println("----------");//match: anyMatch有一个匹配就返回true noneMatch没有任何匹配才返回true allMatch所有匹配才返回trueSystem.out.println(list.stream().anyMatch(x -> x > 4));}/*** 初始化职工列表数据*/private static List<Employee> initEmployee() {List<Employee> employeeList = new ArrayList<>();employeeList.add(new Employee("张三", 8, 3000.0));employeeList.add(new Employee("李四", 18, 5000.0));employeeList.add(new Employee("王五", 28, 7000.0));employeeList.add(new Employee("孙六", 38, 9000.0));return employeeList;}
}

执行程序返回

1
2
3
4
5
----------
1
----------
true

2、按条件匹配filter 

import java.util.*;
import java.util.stream.Collectors;/*** @author qinxun* @date 2023-06-02* @Descripion: 职工测试类*/
public class EmployeeDemo {public static void main(String[] args) {List<Employee> employeeList = initEmployee();// 筛选年纪大于18岁的职工List<Employee> employees = employeeList.stream().filter(s -> s.getAge() > 18).collect(Collectors.toList());System.out.println(employees);}/*** 初始化职工列表数据*/private static List<Employee> initEmployee() {List<Employee> employeeList = new ArrayList<>();employeeList.add(new Employee("张三", 8, 3000.0));employeeList.add(new Employee("李四", 18, 5000.0));employeeList.add(new Employee("王五", 28, 7000.0));employeeList.add(new Employee("孙六", 38, 9000.0));return employeeList;}
}
[Employee{name='王五', age=28, salary=7000.0}, Employee{name='孙六', age=38, salary=9000.0}]

3、聚合max、min、count

import java.util.*;/*** @author qinxun* @date 2023-06-02* @Descripion: 职工测试类*/
public class EmployeeDemo {public static void main(String[] args) {List<Employee> employeeList = initEmployee();// 获取薪水最高的职工Optional<Employee> employeeOptional = employeeList.stream().max(Comparator.comparing(Employee::getSalary, Double::compareTo));System.out.println(employeeOptional.get());// 获取年级最小的职工Optional<Employee> employeeOptional1 = employeeList.stream().min(Comparator.comparing(Employee::getAge, Integer::compareTo));System.out.println(employeeOptional1.get());// 获取年级大于18的职工数量long count = employeeList.stream().filter(s -> s.getAge() > 18).count();System.out.println(count);}/*** 初始化职工列表数据*/private static List<Employee> initEmployee() {List<Employee> employeeList = new ArrayList<>();employeeList.add(new Employee("张三", 8, 3000.0));employeeList.add(new Employee("李四", 18, 5000.0));employeeList.add(new Employee("王五", 28, 7000.0));employeeList.add(new Employee("孙六", 38, 9000.0));return employeeList;}
}
Employee{name='孙六', age=38, salary=9000.0}
Employee{name='张三', age=8, salary=3000.0}
2

4、map与flatMap

/*** @author qinxun* @date 2023-06-02* @Descripion: 职工测试类*/
public class EmployeeDemo {public static void main(String[] args) {List<String> list = Arrays.asList("a","b","c");// map中把小写字母转换成大写List<String> stringList = list.stream().map(String::toUpperCase).collect(Collectors.toList());// 输出[A, B, C]System.out.println(stringList);}
}
/*** @author qinxun* @date 2023-06-02* @Descripion: 职工测试类*/
public class EmployeeDemo {public static void main(String[] args) {String[] arr = {"z-h-a-n-g", "s-a-n"};List<String> list = Arrays.asList(arr);System.out.println(list);// 将两个字符数组合并成一个新的字符数组List<String> collect = list.stream().flatMap(x -> {String[] array = x.split("-");return Arrays.stream(array);}).collect(Collectors.toList());System.out.println(collect);}
}
[z-h-a-n-g, s-a-n]
[z, h, a, n, g, s, a, n]

5、规约reduce 

归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合求和、求乘积和求最值操作。

import java.util.*;/*** @author qinxun* @date 2023-06-02* @Descripion: 职工测试类*/
public class EmployeeDemo {public static void main(String[] args) {List<Employee> list = initEmployee();// 求所有工资的和Double sum = list.stream().map(Employee::getSalary).reduce(0.0, Double::sum);System.out.println(sum);// 求职工工资最大值Optional<Double> max = list.stream().map(Employee::getSalary).reduce((a, b) -> a > b ? a : b);System.out.println(max.get());}/*** 初始化职工列表数据*/private static List<Employee> initEmployee() {List<Employee> employeeList = new ArrayList<>();employeeList.add(new Employee("张三", 8, 3000.0));employeeList.add(new Employee("李四", 18, 5000.0));employeeList.add(new Employee("王五", 28, 7000.0));employeeList.add(new Employee("孙六", 38, 9000.0));return employeeList;}
}
24000.0
9000.0

6、收集(toList、toSet、toMap)

import java.util.*;
import java.util.stream.Collectors;/*** @author qinxun* @date 2023-06-02* @Descripion: 职工测试类*/
public class EmployeeDemo {public static void main(String[] args) {List<Employee> list = initEmployee();// 返回名字做为key,工资做为value的map数据Map<String, Double> employeeMap = list.stream().collect(Collectors.toMap(Employee::getName, Employee::getSalary));System.out.println(employeeMap);// 职工名字集合List<String> employeeNameList = list.stream().map(Employee::getName).collect(Collectors.toList());System.out.println(employeeNameList);// 职工年龄集合Set<Integer> ageSet = list.stream().map(s -> s.getAge()).collect(Collectors.toSet());System.out.println(ageSet);}/*** 初始化职工列表数据*/private static List<Employee> initEmployee() {List<Employee> employeeList = new ArrayList<>();employeeList.add(new Employee("张三", 8, 3000.0));employeeList.add(new Employee("李四", 18, 5000.0));employeeList.add(new Employee("王五", 28, 7000.0));employeeList.add(new Employee("孙六", 38, 9000.0));return employeeList;}
}
{李四=5000.0, 张三=3000.0, 王五=7000.0, 孙六=9000.0}
[张三, 李四, 王五, 孙六]
[18, 38, 8, 28]

7、collect

Collectors提供了一系列用于数据统计的静态方法:

  1. 计数:count
  2. 平均值:averagingInt、averagingLong、averagingDouble
  3. 最值:maxBy、minBy
  4. 求和:summingInt、summingLong、summingDouble
  5. 统计以上所有:summarizingInt、summarizingLong、summarizingDouble
import java.util.*;
import java.util.stream.Collectors;/*** @author qinxun* @date 2023-06-02* @Descripion: 职工测试类*/
public class EmployeeDemo {public static void main(String[] args) {List<Employee> employeeList = initEmployee();// 统计职工人数Long count = employeeList.stream().collect(Collectors.counting());System.out.println(count);// 获取职工最高工资Optional<Double> salaryOptional = employeeList.stream().map(Employee::getSalary).collect(Collectors.maxBy((s1, s2) -> s1.compareTo(s2)));System.out.println(salaryOptional);// 获取职工平均工资Double averageSalary = employeeList.stream().collect(Collectors.averagingDouble(Employee::getSalary));System.out.println(averageSalary);//一次性统计职工所有工资信息DoubleSummaryStatistics summaryStatistics = employeeList.stream().collect(Collectors.summarizingDouble(Employee::getSalary));System.out.println(summaryStatistics);}/*** 初始化职工列表数据*/private static List<Employee> initEmployee() {List<Employee> employeeList = new ArrayList<>();employeeList.add(new Employee("张三", 8, 3000.0));employeeList.add(new Employee("李四", 18, 5000.0));employeeList.add(new Employee("王五", 28, 7000.0));employeeList.add(new Employee("孙六", 38, 9000.0));return employeeList;}
}
4
Optional[9000.0]
6000.0
DoubleSummaryStatistics{count=4, sum=24000.000000, min=3000.000000, average=6000.000000, max=9000.000000}

8、分组(partitioningBy/groupingBy)

import java.util.*;
import java.util.stream.Collectors;/*** @author qinxun* @date 2023-06-02* @Descripion: 职工测试类*/
public class EmployeeDemo {public static void main(String[] args) {List<Employee> employeeList = initEmployee();// 将员工按薪资是否高于7000分组Map<Boolean, List<Employee>> map = employeeList.stream().collect(Collectors.partitioningBy(s -> s.getSalary() > 7000));System.out.println(map);// 将职工按性别分组Map<String, List<Employee>> employeeMap = employeeList.stream().collect(Collectors.groupingBy(Employee::getSex));System.out.println(employeeMap);}/*** 初始化职工列表数据*/private static List<Employee> initEmployee() {List<Employee> employeeList = new ArrayList<>();employeeList.add(new Employee("张三", 8, "男", 3000.0));employeeList.add(new Employee("李四", 18, "女", 5000.0));employeeList.add(new Employee("王五", 28, "男", 7000.0));employeeList.add(new Employee("孙六", 38, "女", 9000.0));return employeeList;}
}
{false=[Employee{name='张三', age=8, salary=3000.0}, Employee{name='李四', age=18, salary=5000.0}, Employee{name='王五', age=28, salary=7000.0}], true=[Employee{name='孙六', age=38, salary=9000.0}]}
{女=[Employee{name='李四', age=18, salary=5000.0}, Employee{name='孙六', age=38, salary=9000.0}], 男=[Employee{name='张三', age=8, salary=3000.0}, Employee{name='王五', age=28, salary=7000.0}]}

9、接合joining 

joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。

import java.util.*;
import java.util.stream.Collectors;/*** @author qinxun* @date 2023-06-02* @Descripion: 职工测试类*/
public class EmployeeDemo {public static void main(String[] args) {List<Employee> employeeList = initEmployee();// 将职工姓名用逗号拼接返回String nameData = employeeList.stream().map(Employee::getName).collect(Collectors.joining(","));System.out.println(nameData);}/*** 初始化职工列表数据*/private static List<Employee> initEmployee() {List<Employee> employeeList = new ArrayList<>();employeeList.add(new Employee("张三", 8, "男", 3000.0));employeeList.add(new Employee("李四", 18, "女", 5000.0));employeeList.add(new Employee("王五", 28, "男", 7000.0));employeeList.add(new Employee("孙六", 38, "女", 9000.0));return employeeList;}
}
张三,李四,王五,孙六

10、排序sorted

import java.util.*;
import java.util.stream.Collectors;/*** @author qinxun* @date 2023-06-02* @Descripion: 职工测试类*/
public class EmployeeDemo {public static void main(String[] args) {List<Employee> employeeList = initEmployee();// 将职工工资升序排序List<Employee> employees = employeeList.stream().sorted(Comparator.comparing(Employee::getSalary)).collect(Collectors.toList());System.out.println(employees);// 将职工工资降序排序List<Employee> list = employeeList.stream().sorted(Comparator.comparing(Employee::getSalary).reversed()).collect(Collectors.toList());System.out.println(list);}/*** 初始化职工列表数据*/private static List<Employee> initEmployee() {List<Employee> employeeList = new ArrayList<>();employeeList.add(new Employee("张三", 8, "男", 3000.0));employeeList.add(new Employee("李四", 18, "女", 5000.0));employeeList.add(new Employee("王五", 28, "男", 7000.0));employeeList.add(new Employee("孙六", 38, "女", 9000.0));return employeeList;}
}
[Employee{name='张三', age=8, salary=3000.0}, Employee{name='李四', age=18, salary=5000.0}, Employee{name='王五', age=28, salary=7000.0}, Employee{name='孙六', age=38, salary=9000.0}]
[Employee{name='孙六', age=38, salary=9000.0}, Employee{name='王五', age=28, salary=7000.0}, Employee{name='李四', age=18, salary=5000.0}, Employee{name='张三', age=8, salary=3000.0}]

11、提取/组合

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;/*** @author qinxun* @date 2023-06-02* @Descripion: 职工测试类*/
public class EmployeeDemo {public static void main(String[] args) {String[] arr1 = {"a", "b", "c", "d"};String[] arr2 = {"d", "e", "f", "g"};Stream<String> stream1 = Stream.of(arr1);Stream<String> stream2 = Stream.of(arr2);// 合并流List<String> newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());System.out.println(newList);// 限制从流中获得前1个数据System.out.println(Stream.of(arr1).limit(1).collect(Collectors.toList()));// 跳过前2个数据System.out.println(Stream.of(arr1).skip(2).collect(Collectors.toList()));}
}
[a, b, c, d, e, f, g]
[a]
[c, d]


http://www.ppmy.cn/news/179874.html

相关文章

安防监控专用工业交换机与普通交换机的区别

工业交换机即工业以太网交换机&#xff0c;它作用是放到路由器后端&#xff0c;来扩展路由器接口&#xff0c;以解决接口不够用的问题。以太网在设计时&#xff0c;由于其采用载波侦听多路复用冲突检测(CSMA/CD机制)&#xff0c;在复杂的工业环境中应用&#xff0c;其可靠性大大…

高清摄像头如何选择工业交换机

网络监控系统在我国的安防中占据了绝对的位置&#xff0c;在高清网络视频监控系统中&#xff0c;经常有客户反馈画面延时、卡顿等现象&#xff0c;造成这种现象的原因有很多&#xff0c;但大多数情况下还是交换机的配置不够合理&#xff0c;导致带宽不足造成的。交换机是整个系…

卡轨式2光8电千兆工业级环网交换机嵌入式低功耗网管型矿用工业以太网交换机

HY5700-7528G-X千兆网管型冗余工业以太网交换机配备多达8个千兆以太网端口&#xff0c;非常适用于构建X-Ring千兆冗余网络&#xff0c;备用的千兆以太网端口可用于上行链路。X-Ring&#xff08;自愈时间<30ms&#xff09;、RSTP/STP和MSTP等以太网冗余技术&#xff0c;增强了…

非网管型工业级交换机产品介绍

非网管型工业级交换机系列产品&#xff0c; EMC工业4级的防护性能&#xff0c;能有效地抵抗静电、雷 击、脉冲的干扰&#xff1b;波纹式高强度铝型材外壳、IP40等级、低功耗设计、抗震的导轨安装。 非网管型工业级交换机产品介绍 产品名称&#xff1a;非网管型工业级交换机 …

高清监控如何选择交换机

网络监控系统在我国的安防中占据了绝对的位置&#xff0c;在高清网络视频监控系统中&#xff0c;经常有客户反啊馈画面延时、卡顿等现象&#xff0c;造成这种现象的原因有很多&#xff0c;但大多数情况下还是交换机的配置不够合理&#xff0c;导致带宽不足造成的。交换机是整个…

天融信数通小百科:喜迎千兆光网的S51200-24S4X交换机

2021年4月召开的国务院常务会议提及&#xff1a;“要加大5G网络和千兆光网建设力度&#xff0c;丰富应用场景。” 随着VR、高清视频、Wi-Fi 6、物联网等新技术在企业网的广泛应用&#xff0c;海量数据传输给传统的铜缆网络带来了巨大压力。 如何对铜缆网络进行升级&#xff…

16光8电全千兆宽温工业交换机16千兆光8千兆网口机架式网管型工业级以太网交换机

8*1000M路以太网电口&#xff0c;16路千兆光接口&#xff0c;支持SNMP网管&#xff0c;18ms内自愈环网保护&#xff0c;工作温度&#xff1a;-40℃&#xff5e;85℃。相对湿度&#xff1a;95% 3RH&#xff08;无凝结&#xff09;。传输距离40km&#xff08;其它数据接入共用&am…

盛科推出新一代超融合网络交换机E550系列

苏州2018年9月12日电 /美通社/ -- 2018年9月11日&#xff0c;国内领先的以太网交换芯片和白牌交换机方案供应商盛科网络&#xff0c;正式宣布推出针对超融合&#xff08;Hyper-Converged Infrastructure&#xff0c;或简称HCI&#xff09;应用场景的新一代交换机E550系列。该方…