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实现一键隐藏屏幕并锁定输入

《使用Python实现一键隐藏屏幕并锁定输入》本文主要介绍了使用Python编写一个一键隐藏屏幕并锁定输入的黑科技程序,能够在指定热键触发后立即遮挡屏幕,并禁止一切键盘鼠标输入,这样就再也不用担心自己... 目录1. 概述2. 功能亮点3.代码实现4.使用方法5. 展示效果6. 代码优化与拓展7. 总结1.

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

Linux中的计划任务(crontab)使用方式

《Linux中的计划任务(crontab)使用方式》:本文主要介绍Linux中的计划任务(crontab)使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、前言1、linux的起源与发展2、什么是计划任务(crontab)二、crontab基础1、cro

kotlin中const 和val的区别及使用场景分析

《kotlin中const和val的区别及使用场景分析》在Kotlin中,const和val都是用来声明常量的,但它们的使用场景和功能有所不同,下面给大家介绍kotlin中const和val的区别,... 目录kotlin中const 和val的区别1. val:2. const:二 代码示例1 Java

C++变换迭代器使用方法小结

《C++变换迭代器使用方法小结》本文主要介绍了C++变换迭代器使用方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、源码2、代码解析代码解析:transform_iterator1. transform_iterat

C++中std::distance使用方法示例

《C++中std::distance使用方法示例》std::distance是C++标准库中的一个函数,用于计算两个迭代器之间的距离,本文主要介绍了C++中std::distance使用方法示例,具... 目录语法使用方式解释示例输出:其他说明:总结std::distance&n编程bsp;是 C++ 标准

vue使用docxtemplater导出word

《vue使用docxtemplater导出word》docxtemplater是一种邮件合并工具,以编程方式使用并处理条件、循环,并且可以扩展以插入任何内容,下面我们来看看如何使用docxtempl... 目录docxtemplatervue使用docxtemplater导出word安装常用语法 封装导出方

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将

使用Jackson进行JSON生成与解析的新手指南

《使用Jackson进行JSON生成与解析的新手指南》这篇文章主要为大家详细介绍了如何使用Jackson进行JSON生成与解析处理,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 核心依赖2. 基础用法2.1 对象转 jsON(序列化)2.2 JSON 转对象(反序列化)3.

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La