Lamda 使用案例

2023-12-31 07:12
文章标签 使用 案例 lamda

本文主要是介绍Lamda 使用案例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • Collect 集合处理
    • Collectors 提供数据统计的静态方法
    • Joining 将stream中元素使用特定连接符拼接,没有则直接连接
    • 分区和分组
    • Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持
    • 收集流处理后元素
  • Filter 筛选器
    • FilterAndColl
  • Foreach_find_match
  • Map_FlatMap
    • FlatMap
    • Map
  • Dinstinct 去重
  • Comparator 自定义比较器

在这里插入图片描述

Collect 集合处理

Collectors 提供数据统计的静态方法

对集合进行数据统计,进行计数、平均值、最值、求和

计数:count
平均值:averagingInt、averagingLong、averagingDouble
最值:maxBy、minBy
求和:summingInt、summingLong、summingDouble
统计以上所有:summarizingInt、summarizingLong、summarizingDouble

 //案例:统计员工人数、平均工资、工资总额、最高工资。public static void main(String[] args) {List<Person> person = Person.getPerson(); 求总数Long count = person.stream().collect(Collectors.counting());//求平均工资Double averageSalary = person.stream().collect(Collectors.averagingDouble(Person::getSalary));//求最高工资Optional<Integer> maxSalary = person.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));// 求工资之和Integer sum = person.stream().collect(Collectors.summingInt(Person::getSalary));// 一次性统计所有信息DoubleSummaryStatistics summarizingSalary = person.stream().collect(Collectors.summarizingDouble(Person::getSalary));System.out.println("员工总数:"+count);System.out.println("平均工资:"+averageSalary);System.out.println("最高工资:"+maxSalary.get());System.out.println("员工工资之和:"+sum);System.out.println("一次性统计员工工资之和:"+summarizingSalary);}

Joining 将stream中元素使用特定连接符拼接,没有则直接连接

 public static void main(String[] args) {List<Person> person = Person.getPerson();//使用,链接所有员工姓名String mans = person.stream().map(Person::getName).collect(Collectors.joining(","));System.out.println("公司所有员工:"+mans);//拼接字符串List<String> strings = Arrays.asList("A", "B", "C", "D");String collect = strings.stream().collect(Collectors.joining("-"));System.out.println(collect);}

分区和分组

分区:按条件将stream分为两个Map,
分组:将集合分为多个map

    public static void main(String[] args) {List<Person> person = Person.getPerson();// 将员工按薪资是否高于8000分组Map<Boolean, List<Person>> collect = person.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));// 将员工按性别分组Map<String, List<Person>> collect1 = person.stream().collect(Collectors.groupingBy(Person::getSex));// 将员工先按性别分组,再按地区分组Map<String, Map<String, List<Person>>> collect2 = person.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));System.out.println("员工薪资是否高于八千分组:" + collect);System.out.println("员工性别分组:" + collect1);System.out.println("员工性别、地区分组:" + collect2);}

Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持

public static void main(String[] args) {/*** 计算员工扣税后薪资总和* */List<Person> person = Person.getPerson();// 每个员工减去起征点后的薪资之和---Collectors.reducing()方式Integer sumWithout = person.stream().collect(Collectors.reducing(0,Person::getSalary, (x, y) -> (x + y - 5000)));System.out.println("员工扣税后薪资总和"+sumWithout);//使用stream的reduce方式Optional<Integer> sumSalary = person.stream().map(Person::getSalary).reduce(Integer::sum);System.out.println("员工薪资总和" + sumSalary.get());}

收集流处理后元素

   public static void main(String[] args) {/*** 收集流处理后元素* 对集合数据对2取余为0的数值分别收集为list和set--set不可重复,6对应的只会存储一份* */List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20);List<Integer> collect = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet());collect.stream().forEach(System.out::println);set.stream().forEach(System.out::print);//员工工资大于8000的姓名和对应属性mapMap<String, Person> map = Person.getPerson().stream().filter(x -> x.getSalary() > 8000).collect(Collectors.toMap(Person::getName, p -> p));System.out.println(map);}

Filter 筛选器

FilterAndColl

筛选工资高于8000的人,并形成新的集合。形成新集合依赖collect

    public static void main(String[] args) {List<Person> persons = Person.getPerson();List<String> collect = persons.stream().filter(x -> x.getSalary() > 7500).map(Person::getName).collect(Collectors.toList());System.out.print("高于8000的员工姓名:" + collect);}

Foreach_find_match

Stream支持类似集合的遍历和匹配元素,Stream中的元素以Optional类型存在

     public static void main(String[] args) {List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);// 遍历输出符合条件的元素list.stream().filter(x -> x > 6).forEach(System.out::println);// 匹配第一个Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst();// 匹配任意(适用于并行流)Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny();// 是否包含符合特定条件的元素boolean anyMatch = list.stream().anyMatch(x -> x < 6);System.out.println("匹配第一个值:" + findFirst.get());System.out.println("匹配任意一个值:" + findAny.get());System.out.println("是否存在大于6的值:" + anyMatch);}

Map_FlatMap

FlatMap

接收一个函数作为参数,将流中的每个值都换成另外一个流,然后把所有流连接成一个流

   public static void main(String[] args) {merge2StrList();}/*** 将两个字符数组合并成一个新的字符数组* */public static void merge2StrList(){List<String> srcList = Arrays.asList("o,o,p,s", "21,11,51,42");List<String> desList = srcList.stream().flatMap(s -> {//将集合的每个元素转化成一个stream流String[] split = s.split(",");Stream<String> stream = Arrays.stream(split);return stream;}).collect(Collectors.toList());System.out.println("转换前的集合:" + srcList);System.out.println("转换后的集合:" + desList);}

Map

接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素

public static void main(String[] args) {demo1();increaseSalary();}/*** 英文字符串数组的元素全部改为大写。整数数组每个元素+3* */public static void demo1(){String[] strArr = { "abcd", "bcdd", "defde", "fTr" };final List<String> strToupper = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());List<Integer> integers = Arrays.asList(77, 8, 45, 12, 11);final List<Integer> addIntegers = integers.stream().map(x -> x + 3).collect(Collectors.toList());System.out.println("都转为大写的字符串是:" + strToupper);System.out.println("都加3的数值是:" + addIntegers);}/***将员工的薪资全部增加1000* */public static void  increaseSalary(){List<Person> personList = Person.getPerson();/*** 改变原来员工集合的方式--新旧集合中的工资都改动* */List<Person> personNewList = personList.stream().map(personT -> {personT.setSalary(personT.getSalary() + 1000);return personT;}).collect(Collectors.toList());System.out.println("改变原集合改动前:" + personList.get(0).getName() + "--" + personList.get(0).getSalary());System.out.println("改变原集合改动后:" + personNewList.get(0).getName() + "--" + personNewList.get(0).getSalary());/*** 不改变原来员工集合的方式--旧集合中的工资未改动* */List<Person> personNewList2 = personList.stream().map(person -> {Person personNew = new Person(person.getName(), 0, 0, null, null);personNew.setSalary(person.getSalary() + 1000);return personNew;}).collect(Collectors.toList());System.out.println("不改变原集合改动前:" + personList.get(0).getName() + "--" + personList.get(0).getSalary());System.out.println("不改变原集合改动后:" + personNewList2.get(0).getName() + "--" + personNewList2.get(0).getSalary());}

Dinstinct 去重

   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);// concat:合并两个流 distinct:去重List<String> collect = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());System.out.println("合并去重后:" + collect);// limit:限制从流中获得前n个数据List<Integer> limit  = Stream.iterate(1, x -> x + 6).limit(3).collect(Collectors.toList());System.out.println("限制从流中获取前三个数据" + limit);// skip:跳过前n个数据List<Integer> skip = Stream.iterate(1, x -> x + 3).limit(6).skip(2).collect(Collectors.toList());System.out.println("跳过前两个数后:" + skip);}

Comparator 自定义比较器

public static void main(String[] args) {List<Integer> integers = Arrays.asList(11, 89, 110, 154, 47, 44);/*** 自然排序* */Optional<Integer> max = integers.stream().max(Integer::compareTo);/*** 自定义排序* */Optional<Integer> max1 = integers.stream().max(new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {return o1.compareTo(o2);}});System.out.println("自然排序的最大值:" + max.get());System.out.println("自定义排序的最大值:" + max1.get());/*** 获取员工工资最高的人* */List<Person> person = Person.getPerson();Optional<Person> maxSalary = person.stream().min(Comparator.comparingInt(Person::getSalary));System.out.println("员工工资最低的人:" + maxSalary.get().getSalary() + "--职员:" + maxSalary.get().getName());}
 public static void main(String [] args){
//        将员工按工资由高到低(工资一样则按年龄由大到小)排序List<Person> person = Person.getPerson();//按员工工资升序排序List<String> sort = person.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList());//按员工工资降序排序List<String> reversedSort = person.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).map(Person::getName).collect(Collectors.toList());System.out.println("升序排序"+sort);System.out.println("降序排序"+reversedSort);//先按工资再按年龄升序排序List<String> salaryThenAge = person.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName).collect(Collectors.toList());System.out.println("先按工资再按年龄升序排序" + salaryThenAge);//先按薪资再按年龄自定义降序排序List<String> collect = person.stream().sorted((a, b) -> {if (a.getSalary() == b.getSalary()) {return b.getAge() - a.getAge();} else {return b.getSalary() - a.getSalary();}}).map(Person::getName).collect(Collectors.toList());System.out.println("自定义先按薪资后按年龄排序" + collect);}

这篇关于Lamda 使用案例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/555335

相关文章

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

C++ Log4cpp跨平台日志库的使用小结

《C++Log4cpp跨平台日志库的使用小结》Log4cpp是c++类库,本文详细介绍了C++日志库log4cpp的使用方法,及设置日志输出格式和优先级,具有一定的参考价值,感兴趣的可以了解一下... 目录一、介绍1. log4cpp的日志方式2.设置日志输出的格式3. 设置日志的输出优先级二、Window

Ubuntu如何分配​​未使用的空间

《Ubuntu如何分配​​未使用的空间》Ubuntu磁盘空间不足,实际未分配空间8.2G因LVM卷组名称格式差异(双破折号误写)导致无法扩展,确认正确卷组名后,使用lvextend和resize2fs... 目录1:原因2:操作3:报错5:解决问题:确认卷组名称​6:再次操作7:验证扩展是否成功8:问题已解