当前位置:网站首页>Lambda表达式案例
Lambda表达式案例
2022-08-03 05:09:00 【*super】
一、语法
//过滤重量为5的水果
List<Fruit> res = fruits.stream().filter(f -> f.getWeight() == 5).collect(Collectors.toList());
//遍历打印过滤后的信息
System.out.println(res);
/*
fruits.stream()将集合变成一个流
.filter(f -> f.getWeight() == 5)表示过滤重量为5的水果
.collect(Collectors.toList());表示将数据收集放入一个新的list里
*/二、方法
1.map、reduce
map表示对流中的每个数据做一个映射函数处理,它不会改变原来的元素,而是会新生成数据
//将集合中的水果对象名称全部取出来获得一个新的名称集合
List<String> res = fruits.stream().map(Fruit::getName).collect(Collectors.toList());
//遍历打印过滤后的信息
res.forEach(System.out::println);
/*
map函数接受一个参数,返回一个值
Fruit::getName是f->f.getName()的缩写,这是Lambda的一个语法糖,理解为如果一个Lambda代表的只是“直接调用这个方法”,那最好还是用名称来调用它,而不是去描述如何调用它
所以整段代码的意思就是将流中的每一个水果对象都取名称,最后将所有名称收集起来放入一个新的list中
*/reduce
//将集合中的水果重量总数统计出来
int totalWeight = fruits.stream().map(Fruit::getWeight).reduce(0, (a, b) -> a + b);
System.out.println(totalWeight);
2.sort、limit、distinct
(1)sort limit
取出集合中重量排名前3的水果
List<Fruit> fruitList = fruits.stream().sorted((f1, f2) -> Integer.compare(f2.getWeight(), f1.getWeight())).limit(3).collect(Collectors.toList());
//遍历打印过滤后的信息
fruitList.forEach(f-> System.out.println(f.toString()));(2)distinct能完成去重的操作
List<Integer> collect = fruits.stream().map(Fruit::getWeight).sorted().distinct().collect(Collectors.toList());
//遍历打印过滤后的信息
collect.forEach(f-> System.out.println(f.toString()));(3) 统计
//最大值
Optional<Integer> optionalMax = fruits.stream().map(Fruit::getWeight).reduce(Integer::max);
//最小值
Optional<Integer> optionalMin = fruits.stream().map(Fruit::getWeight).reduce(Integer::min);
System.out.println(optionalMax.orElse(0));
System.out.println(optionalMin.orElse(0));*(4) 查找
//查看集合中是否有重量为5的数据
boolean match = fruits.stream().anyMatch(fruit -> fruit.getWeight() == 5);
System.out.println(match);
Optional<Fruit> first = fruits.stream().filter(fruit -> fruit.getWeight() == 5).findFirst();
//如果存在就打印水果信息
first.ifPresent(fruit -> System.out.println(fruit.toString()));
/*
anyMatch返回一个bool值表示流中是否存在这样的数据
findFirst()表示从流中查询第一个满足条件的数据
*/三、Lambda表达式案例
1.题目
现在有一个Person类,有姓名,城市,年龄三个属性:
public class Person {
/** * 人名 */
private String name;
/** * 城市名 */
private String city;
/** * 年龄 */
private int age;
get and set、构造方法、tostring。
现在准备好了数据如下:
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("张三","北京",22));
personList.add(new Person("李四","长沙",28));
personList.add(new Person("王五","郑州",17));
personList.add(new Person("赵六","南京",33));
personList.add(new Person("郑七","深圳",40));
personList.add(new Person("李八","上海",36));
personList.add(new Person("陈十","上海",24));
}
}
要求:
找出集合中哪些是上海的
找出集合中最大的年龄和最小的年龄是多少
统计年龄总和
按年龄倒序排序取出前3名
统计集合中出现的城市,要求不能重复
判断集合中是否有姓王的人
找出集合中第一个姓郑的人
2.代码
(1)新建人类
package test;
/**
* @Author:张金贺
* @Date:2022/7/30 9:53
* @Version 1.0
*/
public class Person {
/**
* 人名
*/
private String name;
/**
* 城市名
*/
private String city;
/**
* 年龄
*/
private int age;
public Person() {
}
public Person(String name, String city, int age) {
this.name = name;
this.city = city;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", city='" + city + '\'' +
", age=" + age +
'}';
}
}
(2)添加数据
package test;
import java.util.ArrayList;
import java.util.List;
/**
* @Author:张金贺
* @Date:2022/7/30 9:53
* @Version 1.0
*/
public class main {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("张三","北京",22));
personList.add(new Person("李四","长沙",28));
personList.add(new Person("王五","郑州",17));
personList.add(new Person("赵六","南京",33));
personList.add(new Person("郑七","深圳",40));
personList.add(new Person("李八","上海",36));
personList.add(new Person("陈十","上海",24));
}
}(3)按要求编写
找出集合中哪些是上海的
// 查找地址为上海的人
List<Person> res = personList.stream().filter(f -> f.getCity() == "上海").collect(Collectors.toList());
// 遍历打印过滤后的信息
System.out.println(res);找出集合中最大的年龄和最小的年龄是多少
//最大值
Optional<Integer> optionalMax = personList.stream().map(Person::getAge).reduce(Integer::max);
//最小值
Optional<Integer> optionalMin = personList.stream().map(Person::getAge).reduce(Integer::min);
System.out.println(optionalMax.orElse(0));
System.out.println(optionalMin.orElse(0));统计年龄总和
//将集合中的年龄总和统计出来
int total = personList.stream().map(Person::getAge).reduce(0, (a, b) -> a + b);
System.out.println(total);按年龄倒序排序取出前3名
List<Person> personList1 = personList.stream().sorted((f1, f2) -> Integer.compare(f2.getAge(), f1.getAge())).limit(3).collect(Collectors.toList());
//遍历打印过滤后的信息
personList1.forEach(f-> System.out.println(f.toString()));统计集合中出现的城市,要求不能重复
List<String> collect = personList.stream().map(Person::getCity).sorted().distinct().collect(Collectors.toList());
//遍历打印过滤后的信息
collect.forEach(f-> System.out.println(f.toString()));判断集合中是否有姓王的人
// 判断集合中是否有姓王的人
boolean match = personList.stream().anyMatch(f -> f.getName() == "王五");
System.out.println(match);
找出集合中第一个姓郑的人
// 找出集合中第一个姓郑的人
Optional<Person> first = personList.stream().filter(names -> names.getName() == "郑七").findFirst();
//如果存在就打印信息
first.ifPresent(names -> System.out.println(names.toString()));(4)综合
package test;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* @Author:张金贺
* @Date:2022/7/30 9:53
* @Version 1.0
*/
public class main {
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("张三","北京",22));
personList.add(new Person("李四","长沙",28));
personList.add(new Person("王五","郑州",17));
personList.add(new Person("赵六","南京",33));
personList.add(new Person("郑七","深圳",40));
personList.add(new Person("李八","上海",36));
personList.add(new Person("陈十","上海",24));
// 查找地址为上海的人
List<Person> res = personList.stream().filter(f -> f.getCity() == "上海").collect(Collectors.toList());
// 遍历打印过滤后的信息
System.out.println(res);
System.out.println("-----------------------------------------------------");
//最大值
Optional<Integer> optionalMax = personList.stream().map(Person::getAge).reduce(Integer::max);
//最小值
Optional<Integer> optionalMin = personList.stream().map(Person::getAge).reduce(Integer::min);
System.out.println(optionalMax.orElse(0));
System.out.println(optionalMin.orElse(0));
System.out.println("-----------------------------------------------------");
//将集合中的年龄总和统计出来
int total = personList.stream().map(Person::getAge).reduce(0, (a, b) -> a + b);
System.out.println(total);
System.out.println("-----------------------------------------------------");
List<Person> personList1 = personList.stream().sorted((f1, f2) -> Integer.compare(f2.getAge(), f1.getAge())).limit(3).collect(Collectors.toList());
//遍历打印过滤后的信息
personList1.forEach(f-> System.out.println(f.toString()));
System.out.println("-----------------------------------------------------");
List<String> collect = personList.stream().map(Person::getCity).sorted().distinct().collect(Collectors.toList());
//遍历打印过滤后的信息
collect.forEach(f-> System.out.println(f.toString()));
System.out.println("-----------------------------------------------------");
// 判断集合中是否有姓王的人
boolean match = personList.stream().anyMatch(f -> f.getName() == "王五");
System.out.println(match);
System.out.println("-----------------------------------------------------");
// 找出集合中第一个姓郑的人
Optional<Person> first = personList.stream().filter(names -> names.getName() == "郑七").findFirst();
//如果存在就打印信息
first.ifPresent(names -> System.out.println(names.toString()));
System.out.println("-----------------------------------------------------");
}
}
边栏推荐
猜你喜欢

接口测试框架实战(四)| 搞定 Schema 断言

社交电商:链动2+1模式,为什么能在电商行业生存那么久?

三丁基-巯基膦烷「tBuBrettPhos Pd(allyl)」OTf),1798782-17-8

Jmeter 模拟多用户登录的两种方法

接口测试框架实战 | 流程封装与基于加密接口的测试用例设计

13.
lt.647. Palindromic substring + lt.516. Longest palindrome subsequence 
Unity2D horizontal board game tutorial 6 - enemy AI and attack animation

Ali cloud object storage oss private barrels to generate links

荧光标记多肽FITC/AMC/FAM/Rhodamine/TAMRA/Cy3/Cy5/Cy7-Peptide

Shell conditional statement judgment
随机推荐
MCM box model modeling method and source analysis of atmospheric O3
【Harmony OS】【ARK UI】ets use startAbility or startAbilityForResult to invoke Ability
Presto installation and deployment tutorial
typescript40-class类的保护修饰符
【Harmony OS】【ARK UI】轻量级数据存储
JS底层手写
超好用的画图工具推荐
2022/08/02 学习笔记 (day22) 多线程
Kotlin-Flow常用封装类:StateFlow的使用
修饰生物素DIAZO-生物素-PEG3-DBCO|重氮-生物素-三聚乙二醇-二苯基环辛炔
typescript45-接口之间的兼容性
业务表解析-余额系统
【Harmony OS】【FAQ】Hongmeng Questions Collection 1
【精讲】利用原生js实现todolist
接口测试实战| GET/POST 请求区别详解
[Developers must see] [push kit] Collection of typical problems of push service service 2
FileZilla 搭建ftp服务器
unity2D横板游戏教程6-敌人AI以及受击动画
2. 两数相加
【Biotin Azide|cas:908007-17-0】Price_Manufacturer