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

相关文章

Java Jackson核心注解使用详解

《JavaJackson核心注解使用详解》:本文主要介绍JavaJackson核心注解的使用,​​Jackson核心注解​​用于控制Java对象与JSON之间的序列化、反序列化行为,简化字段映射... 目录前言一、@jsonProperty-指定JSON字段名二、@JsonIgnore-忽略字段三、@Jso

MySQL中隔离级别的使用详解

《MySQL中隔离级别的使用详解》:本文主要介绍MySQL中隔离级别的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录引言undo log的作用MVCC的实现有以下几个重要因素如何根据这些因素判断数据值?可重复读和已提交读区别?串行化隔离级别的实现幻读和可

使用Python和SQLAlchemy实现高效的邮件发送系统

《使用Python和SQLAlchemy实现高效的邮件发送系统》在现代Web应用中,邮件通知是不可或缺的功能之一,无论是订单确认、文件处理结果通知,还是系统告警,邮件都是最常用的通信方式之一,本文将详... 目录引言1. 需求分析2. 数据库设计2.1 User 表(存储用户信息)2.2 CustomerO

9个SpringBoot中的自带实用过滤器使用详解

《9个SpringBoot中的自带实用过滤器使用详解》在SpringBoot应用中,过滤器(Filter)是处理HTTP请求和响应的重要组件,SpringBoot自带了许多实用的过滤器,如字符编码,跨... 目录1. CharacterEncodingFilter - 字符编码过滤器功能和配置手动配置示例2

Redis持久化机制之RDB与AOF的使用

《Redis持久化机制之RDB与AOF的使用》:本文主要介绍Redis持久化机制之RDB与AOF的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Redis持久化机制-RDB与AOF一、RDB持久化机制1、RDB简介2、RDB的工作原理3、RDB的优缺点4

使用Python实现实时金价监控并自动提醒功能

《使用Python实现实时金价监控并自动提醒功能》在日常投资中,很多朋友喜欢在一些平台买点黄金,低买高卖赚点小差价,但黄金价格实时波动频繁,总是盯着手机太累了,于是我用Python写了一个实时金价监控... 目录工具能干啥?手把手教你用1、先装好这些"食材"2、代码实现讲解1. 用户输入参数2. 设置无头浏

Spring Boot 常用注解详解与使用最佳实践建议

《SpringBoot常用注解详解与使用最佳实践建议》:本文主要介绍SpringBoot常用注解详解与使用最佳实践建议,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录一、核心启动注解1. @SpringBootApplication2. @EnableAutoConfi

mysql递归查询语法WITH RECURSIVE的使用

《mysql递归查询语法WITHRECURSIVE的使用》本文主要介绍了mysql递归查询语法WITHRECURSIVE的使用,WITHRECURSIVE用于执行递归查询,特别适合处理层级结构或递归... 目录基本语法结构:关键部分解析:递归查询的工作流程:示例:员工与经理的层级关系解释:示例:树形结构的数

Redis中RedisSearch使用及应用场景

《Redis中RedisSearch使用及应用场景》RedisSearch是一个强大的全文搜索和索引模块,可以为Redis添加高效的搜索功能,下面就来介绍一下RedisSearch使用及应用场景,感兴... 目录1. RedisSearch的基本概念2. RedisSearch的核心功能(1) 创建索引(2

Redis中HyperLogLog的使用小结

《Redis中HyperLogLog的使用小结》Redis的HyperLogLog是一种概率性数据结构,用于统计唯一元素的数量(基数),本文主要介绍了Redis中HyperLogLog的使用小结,感兴... 目录 一、HyperlogLog 是什么?️ 二、使用方法1. 添加数据2. 查询基数China编程3.