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

相关文章

C#中checked关键字的使用小结

《C#中checked关键字的使用小结》本文主要介绍了C#中checked关键字的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录✅ 为什么需要checked? 问题:整数溢出是“静默China编程”的(默认)checked的三种用

C#中预处理器指令的使用小结

《C#中预处理器指令的使用小结》本文主要介绍了C#中预处理器指令的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录 第 1 名:#if/#else/#elif/#endif✅用途:条件编译(绝对最常用!) 典型场景: 示例

mysql_mcp_server部署及应用实践案例

《mysql_mcp_server部署及应用实践案例》文章介绍了在CentOS7.5环境下部署MySQL_mcp_server的步骤,包括服务安装、配置和启动,还提供了一个基于Dify工作流的应用案例... 目录mysql_mcp_server部署及应用案例1. 服务安装1.1. 下载源码1.2. 创建独立

Mysql中RelayLog中继日志的使用

《Mysql中RelayLog中继日志的使用》MySQLRelayLog中继日志是主从复制架构中的核心组件,负责将从主库获取的Binlog事件暂存并应用到从库,本文就来详细的介绍一下RelayLog中... 目录一、什么是 Relay Log(中继日志)二、Relay Log 的工作流程三、Relay Lo

使用Redis实现会话管理的示例代码

《使用Redis实现会话管理的示例代码》文章介绍了如何使用Redis实现会话管理,包括会话的创建、读取、更新和删除操作,通过设置会话超时时间并重置,可以确保会话在用户持续活动期间不会过期,此外,展示了... 目录1. 会话管理的基本概念2. 使用Redis实现会话管理2.1 引入依赖2.2 会话管理基本操作

Springboot请求和响应相关注解及使用场景分析

《Springboot请求和响应相关注解及使用场景分析》本文介绍了SpringBoot中用于处理HTTP请求和构建HTTP响应的常用注解,包括@RequestMapping、@RequestParam... 目录1. 请求处理注解@RequestMapping@GetMapping, @PostMappin

mybatis-plus分表实现案例(附示例代码)

《mybatis-plus分表实现案例(附示例代码)》MyBatis-Plus是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生,:本文主要介绍my... 目录文档说明数据库水平分表思路1. 为什么要水平分表2. 核心设计要点3.基于数据库水平分表注意事项示例

springboot3.x使用@NacosValue无法获取配置信息的解决过程

《springboot3.x使用@NacosValue无法获取配置信息的解决过程》在SpringBoot3.x中升级Nacos依赖后,使用@NacosValue无法动态获取配置,通过引入SpringC... 目录一、python问题描述二、解决方案总结一、问题描述springboot从2android.x

SpringBoot整合AOP及使用案例实战

《SpringBoot整合AOP及使用案例实战》本文详细介绍了SpringAOP中的切入点表达式,重点讲解了execution表达式的语法和用法,通过案例实战,展示了AOP的基本使用、结合自定义注解以... 目录一、 引入依赖二、切入点表达式详解三、案例实战1. AOP基本使用2. AOP结合自定义注解3.

Python中Request的安装以及简单的使用方法图文教程

《Python中Request的安装以及简单的使用方法图文教程》python里的request库经常被用于进行网络爬虫,想要学习网络爬虫的同学必须得安装request这个第三方库,:本文主要介绍P... 目录1.Requests 安装cmd 窗口安装为pycharm安装在pycharm设置中为项目安装req