Lambda表达式案例

一、语法

 //过滤重量为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("-----------------------------------------------------");
    }

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java张金贺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值