首页 > 编程语言 >Java8之Stream的学习

Java8之Stream的学习

时间:2023-06-03 17:08:36浏览次数:70  
标签:stream Stream List 学习 add employeeList Employee new Java8

一、概念理解

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);
        // foreach
        list.forEach(System.out::println);
 
        System.out.println("----------");
 
        //find
        Optional<Integer> firstData = list.stream().findFirst();
        System.out.println(firstData.get());
 
        System.out.println("----------");
 
        //match: anyMatch有一个匹配就返回true noneMatch没有任何匹配才返回true allMatch所有匹配才返回true
        System.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);
    }
}

flatMap把两个数据流合并成一个数据流

[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提供了一系列用于数据统计的静态方法:

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


计数:count

平均值:averagingInt、averagingLong、averagingDouble

最值:maxBy、minBy

求和:summingInt、summingLong、summingDouble

统计以上所有: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、提取/组合(distinct/limit/skip)
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]

标签:stream,Stream,List,学习,add,employeeList,Employee,new,Java8
From: https://blog.51cto.com/u_13312531/6408205

相关文章

  • 机器学习入门基础:机器学习实践
    目录7.1数据集划分7.1.1训练集、验证集和测试集划分7.1.2交叉验证7.1.3不平衡数据处理7.2评价指标7.2.1回归的评价指标7.2.2分类的评价指标7.2.3评价指标案例7.3正则化、偏差和方差7.3.1欠拟合和过拟合7.3.2正则化7.3.3偏差和方差参考文献7.1数据集划分7.1.1训练集......
  • JDK 8新特性:Stream流的创建
         ......
  • JDK 8新特性:Stream流入门
          ......
  • 04web安全学习---PHP表单验证
    一、什么是表单?二、如何创建一个表单表单的一个最简单的写法:<formaction="https://www.baidu.com/s"><inputname='wd'/><inputtype='submit'/></form><!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"&quo......
  • 【什么是CNN】入门学习随笔
    什么是CNN?https://www.bilibili.com/video/BV1zF411V7xu/?p=6&share_source=copy_web&vd_source=3a1ed9fe9b3eb506d95e8709e124a7ce CNN最基本的架构:卷积层、池化层、全连接层带参数计算才能算一层:卷积和全连接池化:一般选最大值转换:转换成向量感受野:下图为5*5......
  • FreeRtos的移植,以及一些嵌入式学习心得。
    不得不先提心得。这不是第一次移植FreeRtos,至少是五六七八九次了,当然也不是最后一次。但是每一次移植其实都差不多,并没有什么得心应手的感觉。原因就是学的东西太多,学的太杂。我不得不承认,就算我天资聪慧,异于常人,记这么多知识是不可能的。人力有穷时。尊重这个客观现实,但不放......
  • 英语学习
     1.祈使句的反义疑问句 2. 3. 4. 5.can`thelpdoing忍不住做某事6. 7. 8.Wouldyouliketodosth?你愿意做某事吗?9. 10. 11. 12.表示频率的:onceaweek,twiceamonththree timesaweekfourtimesaweek13.lookf......
  • JavaScript学习笔记:浏览器事件
    概念客户端JavaScript程序使用异步事件驱动的编程模型。浏览器会在文档、浏览器或某些元素或与之关联的对象发生某些事情时生成事件对象。比如文档加载完成、敲击键盘输入等。JavaScript程序可以给某些对象绑定监听器函数来监听特定的事件,在该对象上发生指定事件时,这些函数会被......
  • golang 学习之 etcd protobuffer grpc gorm 服务注册发现 go-micro
    1.etcd使用步骤1)下载:https://github.com/etcd-io/etcd/releases/2)配置环境变量3)编辑local-cluster-profile文件:(利用goreman启动方式,生产环境参考官方文档)etcd1:etcd--nameinfra1--listen-client-urlshttp://127.0.0.1:2379--advertise-client-urlshttp://127.0.0.1......
  • 《Just For Fun》:学习即游戏
    《JustForFun》:学习即游戏最近读完了Linus的自传《JustForFun》,一直想写点东西,但始终苦于工作繁忙,无暇思考该从何写起。技术上自然不用废话,Linux的存在对于业界的贡献天下皆知,写什么都是画蛇添足。仔细回想读这本书的过程,我始终在意的是作者的思想,他对于技术生活的想法,我......