Lambda表达式学习

lambda表达式

Lambda是JDK8中一个语法糖,它可以对某些匿名内部类的写法进行简化。它是函数式编程思想的一个重要体现,让我们不用关注是什么对象,而是关注我们对数据进行了什么操作。

基本格式:
(参数列表) -> {代码}
例1:
我们在创建线程并启动时可以使用匿名内部类的写法

new Thread(new Runnable(){
    @Override
    public void run() {
        System.out.println("新线程中的run方法被执行了");
    }
}).start();
        new Thread(()->{
                System.out.println("新线程中的run方法被执行了");
        }).start();

例2:

    public static int calculateNum(IntBinaryOperator operator) {
        int a = 10;
        int b = 20;
        return operator.applyAsInt(a, b);
    }
        calculateNum(new IntBinaryOperator() {
            @Override
            public int applyAsInt(int left, int right) {
                return left+right;
            }
        });
//转换后
        System.out.println(calculateNum((left,right) -> {
            return left + right;
        }));

例3:

    public static void printNum(IntPredicate predicate) {
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        for (int i : arr) {
            if (predicate.test(i)) {
                System.out.println(i);
            }
        }
    }
        printNum(new IntPredicate() {
            @Override
            public boolean test(int value) {
                return value%2==0;
            }
        });

        printNum((value)->{
            return value%2==0;
        });

省略规则

  • 参数类型可以省略
  • 方法体只有一句代码时大括号return和唯一一句代码的分号可以省略
  • 方法只有一个参数时,小括号可以省略
  • 以上规则都可以省略不记,使用idea的快捷键 alt+enter

stream流

Java8的Stream使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式的操作,可以更方便的让我们对集合或数组操作。

入门案例

案例准备:

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode  // 去重
public class Author {
    private Long id;
    private String name;
    private Integer age;
    private String intro;
    private List<Book> books;
}

@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Book {
    private Long id;
    private String name;
    private String category;
    private Integer score;
    private String intro;
}

public class StreamDemo {

    private static List<Author> getAuthors() {
        Author author = new Author(1L, "蒙多", 17, "一个祖安人", null);
        Author author2 = new Author(2L, "亚拉索", 18, "艾欧尼亚", null);
        Author author3 = new Author(3L, "易大师", 19, "黑色玫瑰", null);
        Author author4 = new Author(3L, "易大师", 19, "黑色玫瑰", null);

        List<Book> book1 = new ArrayList<>();
        List<Book> book2 = new ArrayList<>();
        List<Book> book3 = new ArrayList<>();
        List<Book> book4 = new ArrayList<>();

        book1.add(new Book(1L,"*","哲学,爱情", 80, "*"));
        book1.add(new Book(2L,"**","爱情,个人成长", 80, "**"));

        book2.add(new Book(3L,"***","爱情,传记", 70, "***"));
        book2.add(new Book(3L,"****","个人成长,传记", 70, "****"));
        book2.add(new Book(4L,"*****","哲学", 70, "*****"));

        book3.add(new Book(5L,"******","个人成长", 60, "******"));
        book3.add(new Book(6L,"*******","传记", 60, "*******"));
        book3.add(new Book(6L,"********","爱情", 60, "********"));

        book4.add(new Book(5L,"******","个人成长", 60, "******"));
        book4.add(new Book(6L,"*******","个人成长,传记,爱情", 60, "*******"));
        book4.add(new Book(6L,"********","哲学,爱情,个人成长", 60, "********"));


        author.setBooks(book1);
        author2.setBooks(book2);
        author3.setBooks(book3);
        author4.setBooks(book4);

        List<Author> authors = new ArrayList<>(Arrays.asList(author,author2,author3,author4));
        return authors;
    }
}

案例:获取到作家的集合,打印出年龄小于18的作家的名字

    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        authors.stream()
                .distinct()
                .filter(author -> author.getAge()<18)
                .forEach(author -> System.out.println(author));

    }

常用操作

创建流

单例集合:集合对象.stream()

List<Integer> list = new ArrayList<>();
Stream<Integer> stream = list.stream();

数组:Arrays.stream(数组) 或 Stream.of(数组) 来创建

Integer[] arr = {1,2,2,3,4};
Arrays.stream(arr).distinct().forEach(item-> System.out.println(item));

双例集合:转换成单例集合后再创建

        Map<String, Integer> map = new HashMap<>();
        map.put("蜡笔小新", 18);
        map.put("黑子", 15);
        map.put("日向雏田", 17);
        map.entrySet().stream()
                .filter(stringIntegerEntry -> stringIntegerEntry.getValue()>15)
                .forEach(stringIntegerEntry -> System.out.println(stringIntegerEntry.getKey()+":"+stringIntegerEntry.getValue()));

中间操作

1、filter
对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。

    /**
     * 作者名称长度大于2的作者
     * */
    @Test
    public void test01(){
        List<Author> authors = getAuthors();
        authors.stream().filter(item->item.getName().length()>2)
                .forEach(item-> System.out.println(item));
    }

2、map
可以把流中的元素进行计算或转换。

    /**
     * 打印所有作家的名称
     * */
    @Test
    public void test02(){
        getAuthors().stream()
                .map(author -> author.getName())
                .forEach(item-> System.out.println(item));
    }

3、distinct
去除流中的重复元素。
注意:distinct方法是依赖Object的equals方法来判断是否是相同对象,所以需要重写equals方法。
4、sorted
对流中的元素进行排序。
方式一:调用sorted()空参方法
在比较的实体类上要实现Comparable接口,不然会报类型不匹配的异常。
[外链图片转存中…(img-jIMbXVcO-1713248957017)]

public static void test2() {
    List<Author> authors = getAuthors();
    authors.stream()
            .distinct()
            .sorted()
            .forEach(author -> System.out.println(author.getAge()));
}

方式二:在sorted方法中实现Comparator接口

    @Test
    public void test03(){
        getAuthors().stream()
                .distinct()
                .sorted((o1, o2) -> o1.getAge()-o2.getAge()) //o1-o2:升序 o2-o1:降序
                .forEach(item-> System.out.println(item));
    }

5、limit
可以设置流的最大长度,超出的部分将被抛弃。

    /**
     * limit
     * */
    @Test
    public void test04(){
        getAuthors().stream()
                .sorted((o1, o2) -> o2.getAge()-o1.getAge())
                .limit(2)
                .forEach(item-> System.out.println(item));
    }

6、skip
跳过流中的前n个元素,返回剩下的元素。

    /**
     * skip
     * */
    @Test
    public void test05(){
        getAuthors().stream()
                .distinct()
                .sorted()
                .skip(1)
                .forEach(item-> System.out.println(item));
    }

7、flatMap
map只能把一个对象转换成另一个对象来作为流中的元素。而flatMap可以把一个对象转换成多个对象作为流中的元素。
案例1:打印所有书籍的名字,要求对重复的元素进行去重。
map方式:Author对象的books属性是集合类型,使用原来map转换对象,要使用嵌套循环进行打印。

    /**
     * flatMap
     * 打印所有书籍的名字,要求对重复的元素进行去重。
     * */
    @Test
    public void test06(){
        getAuthors()
                .stream()
                .flatMap(item->item.getBooks().stream())
                .distinct()
                .forEach(item-> System.out.println(item));
    }

案例二:打印现有数据的所有分类,要求对分类进行去重。不能出现这种格式:哲学,爱情,要将它们拆开输出。

    /**
     * flatMap
     * 案例二:打印现有数据的所有分类,要求对分类进行去重。不能出现这种格式:哲学,爱情,要将它们拆开输出。
     * */ 
    @Test
    public void test07(){
        getAuthors()
                .stream()
                .flatMap(item->item.getBooks().stream().flatMap(book-> Arrays.stream(book.getCategory().split(","))))
                .distinct()
                .forEach(item-> System.out.println(item));
    }

终结操作

1、forEach
对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。
2、count
获取当前流中元素的个数。

//打印这些作家的所出书籍的数量
public static void test4() {
    List<Author> authors = getAuthors();
    long count = authors.stream()
            .flatMap(author -> author.getBooks().stream())
            .distinct()
            .count();
    System.out.println(count);
}

3、max&min
获取流中的最值

    /**
     * max&min
     * 分别获取这些作家所出书籍的最高分和最低分
     * */
    @Test
    public void test08(){
        Optional<Integer> max = getAuthors().stream()
                .flatMap(item -> item.getBooks().stream())
                .map(item -> item.getScore())
                .max((o1, o2) -> o1 - o2);
        System.out.println(max.get());
    }

4、collect
把当前流转换成一个集合。
list集合

    /**
     * list
     * 获取一个存放所有作者名字的list集合
     * */
    @Test
    public void test09(){
        List<String> list = getAuthors().stream()
                .map(item -> item.getName())
                .collect(Collectors.toList());
    }

set集合

    /**
     * set
     * 获取一个存放所有作者的数书的set集合
     * */
    @Test
    public void test10(){
        Set<String> collect = getAuthors().stream()
                .flatMap(item -> item.getBooks().stream())
                .map(item -> item.getName())
                .collect(Collectors.toSet());
    }

map集合

    /**
     * map
     * //获取一个Map集合,map的key为作者名,value为List<Book>
     * */
    @Test
    public void test11(){
        Map<String, List<Book>> collect = getAuthors().stream()
                .distinct()
                .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
        System.out.println(collect);
    }

5、查找与匹配
(1)anyMatch:判断是否有任意符合匹配条件的元素,结果为boolean类型。

    /**
     * anyMatch
     *判断是否有作家年龄在18以上
     * */
    @Test
    public void test12(){
        getAuthors().stream()
                .anyMatch(item->item.getAge()>18);
    }

(2)allMatch:判断是否都符合条件,如果都符合返回true,否则返回false

    /**
     * 判断是否所有作家年龄在18以上
     * allMatch
     * */
    @Test
    public void test13(){
        getAuthors().stream()
                .allMatch(item->item.getAge()>18);
    }

(3)noneMatch:判断流中的元素是否都不符合匹配条件,如果都不符合结果为true,否则结果为false。
(4)findAny:获取流中的任意一个元素。该方法没有办法保证获取到的一定是流中的第一个元素。

    /**
     * findAll
     * 获取任意一个年龄大于18的作家,如果存在就输出他的名字
     * */

    @Test
    public void test14(){
        getAuthors().stream()
                .filter(item->item.getAge()>18)
                .findAny()
                .ifPresent(item-> System.out.println(item.getName()));
    }

(5)findFirst:获取流中的第一个元素。

    /**
     * findFirst
     * 获取一个年龄最小的作家,并输出他的姓名
     * */
    @Test
    public void test15(){
        System.out.println(getAuthors().stream()
                .sorted((o1, o2) -> o1.getAge() - o2.getAge())
                .findFirst());
    }

(6)reduce归并
对流中的数据按照你指定的计算方式计算出一个结果。(缩减操作)
reduce的作用是把stream中的元素给组合起来。我们可以传入一个初始值,它会按照我们的计算方式依次拿流中的元素和初始化值进行计算,计算结果再和后面的元素计算。
它内部的计算方式如下:

T result = identity;
for (T element : this stream)
	result = accumulator.apply(result, element)
return result;

其中identity就是我们可以通过方法参数传入的初始值,accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。
案例1:使用reduce求所有作者年龄的和

    /**
     * reduce
     * 使用reduce求所有作者年龄的和
     * */
    @Test
    public void test16(){
        Integer age = getAuthors().stream()
                .map(item -> item.getAge())
                .reduce(0, (integer, integer2) -> integer + integer2);
        System.out.println(age);
    }

案例2:使用reduce求所有作者中年龄的最大值

/**
     * reduce
     * 使用reduce求所有作者年龄的最大值
     * */
@Test
public void test17(){
    Integer age = getAuthors().stream()
    .map(item -> item.getAge())
    .reduce(Integer.MIN_VALUE, (result, element) -> result>element?result:element) ;
    System.out.println(age);
}

单参数reduce求最小值案例:

    /**
     * reduce一个参数
     * 使用reduce求所有作者年龄的最小值
     * */
    @Test
    public void test18(){
        Optional<Integer> age = getAuthors().stream()
                .map(item -> item.getAge())
                .reduce((result, element) -> result>element?element:result);
        System.out.println(age.get());
    }

Optional

我们在编写代码的时候出现最多的就是空指针异常,所以在很多情况下我们需要做各种非空的判断。尤其是对象中的属性还是一个对象的情况下,这种判断会更多。

Author author = getAuthor();
if(author != null) {
	sout(author.getName());
}

过多的判断语句会让我们的代码显得臃肿,所以在JDK8中引入了Optional,养成使用Optional的习惯后,你可以写出更优雅的代码来避免空指针异常。
创建对象
Optional就好像是包装类,可以把我们的具体数据封装到Optional对象内部,然后我们去使用Optional中封装好的方法 操作封装进去的数据,就可以非常优雅的避免空指针异常。
我们一般使用Optional的静态方法ofNullable来把数据封装成一个Optional对象,无论传入的参数是否为null都不会出现问题。

    @Test
    public void test01(){
        Optional<Author> author = Optional.ofNullable(getAuthor());
        System.out.println(author);
    }

    public  Author getAuthor(){
        Author  author = new Author(1L, "蒙多", 17, "一个祖安人", null);
        return author;
    }

如果你可以确定一个对象不为空,则可以使用Optional的静态方法of来把数据封装成Optional对象。

Author author = new Author();
Optional<Author> optionalAuthor = Optional.of(author);

orElseGet()

    /**
     * orElseGet
     * */
    @Test
    public void test02(){
        Optional<Author> author = getAuthor();
        System.out.println(author.orElseGet(() -> new Author(1L, "蒙多", 17, "一个祖安人", null)));
    }

orElseThrow()

    /**
     * orElseThrow
     * */
    @Test
    public void test03() throws Throwable {
        Optional<Author> author = getAuthor();
        System.out.println(author.orElseThrow(() -> new Throwable("数据为null")));
    }

过滤

我们可以使用filter方法对数据进行过滤。如果原本是有数据的,但不符合判断条件,也会变成一个无数据的Optional对象。

    /**
     * filter
     * */
    @Test
    public void test04() throws Throwable {
        Optional<Author> author = getAuthor();
        System.out.println(author.filter(author1 -> author1.getAge() > 15));
    }

判断

我们可以使用isPresent方法进行判断是否存在数据的判断。如果为空,返回值为false,如果不为空,返回值为true。
但这种方式不能体现Optional的好处,更推荐使用ifPresent方法。

    /**
     * ifPresent()
     * */
    @Test
    public void test05() throws Throwable {
        Optional<Author> author = getAuthor();
        author.filter(item -> item.getAge() > 12).ifPresent(item-> System.out.println(item));
    }

数据转换

Optional还提供了map可以让我们的数据进行转换,并且转换得到的数据也还是Optional包装好的,保证了我们的使用安全。

    /**
     * map
     * */
    @Test
    public void test06() throws Throwable {
        Optional<Author> author = getAuthor();
        Optional<List<Book>> books = author.map(item -> item.getBooks());
        books.ifPresent(item-> System.out.println(item));
    }

函数式接口

只有一个抽象方法的接口我们称为函数接口。
JDK的函数式接口都加上了@FunctionalInterface注解进行标识。但是无论是否加上该注解,只要接口中只有一个抽象方法,就是函数式接口。

常见函数式接口

Consumer 消费接口
根据其中抽象方法的参数列表和返回值类型可以知道,我们可以在方法中对传入的参数进行消费。
[外链图片转存中…(img-G3ivE49p-1713248957018)]
Function 计算转换接口
根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数计算或转换,把结果返回。
[外链图片转存中…(img-ClkrVXLu-1713248957019)]
Predicate 判断接口
根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数条件判断,返回判断结果。
[外链图片转存中…(img-lQEY250a-1713248957019)]
Supplier 生产型接口
根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中创建对象,把创建好的对象返回。[外链图片转存中…(img-1ADRsl2M-1713248957019)]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值