Lambda表达式

Lambda表达式

表达式的特点

  • 可选类型声明:不需要声明参数类型,编译器可以统一识别参数值。
  • 可选的参数圆括号:一个参数无需定义圆括号,但多个参数需要定义圆括号。
  • 可选的大括号:如果主体包含了一个语句,就不需要使用大括号。
  • 可选的返回关键字:如果主体只有一个表达式返回值则编译器会自动返回值,大括号需要指定表达式返回了一个数值

Lambda在集合当中的使用

1.List和forEach、sort

forEach()方法遍历集合,如果要打印元素,它需要的实现 Consumer接口,同时要实现重写accept()方法,它会把数组里的每一个元素都交给,accept()方法。

/**
 * @author Summer
 * @date 22/08/25
 */
@Slf4j
public class CollectionTest1 {
    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<>();
        list.add("Hello");
        list.add("Summer");

        list.forEach(new Consumer<String>(){
            /**
             * Performs this operation on the given argument.
             *
             * @param s the input argument
             */
            @Override
            public void accept(String s) {
                log.info(s);
            }

        });

        System.out.println("==========================");
        list.forEach(a-> System.out.println(a));
    }
}

输出
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Un8qKw3X-1661583418043)(http://apidoc.jadinec.com//server/index.php?s=/api/attachment/visitFile&sign=624baee4d815bc85313817fda297cf0b)]

sort方法
list.sort(new Comparator<String>(){

    @Override
    public int compare(String o1, String o2) {
        return o1.compareTo(o2);
    }
});
System.out.println(list);
System.out.println("===================");
//再添加一个元素tomorrow
list.add("tomorrow");
//默认是升序
list.sort(((o1, o2) -> o1.compareTo(o2)));
System.out.println(list);

Hashmap的forEach

/**
 * @author Summer
 * @date 22/08/25
 */
public class HashmapTest {
    public static void main(String[] args) {
        HashMap<Integer,String> hashMap = new HashMap();
        hashMap.put(1,"Spring");
        hashMap.put(2,"Summer");
        hashMap.put(3,"autumn");
        hashMap.put(4,"winter");
		//此时并未使用lambda表达式,较为繁琐
        hashMap.forEach(new BiConsumer<Integer, String>() {
            @Override
            public void accept(Integer k, String v) {
                System.out.println(k+"-->"+v);
            }
        });
        System.out.println("=========================");
		//只需要一句即可
        hashMap.forEach((k,v)-> System.out.println(k+"-->"+v));
    }
}
list.stream().foreach()和list.foreach()的对比
  1. 执行顺序
    Collection.forEach()使用集合的迭代器(如果指定了一个),集合里元素的处理顺序是明确的。相反,Collection.stream().forEach()的处理顺序是不明确的。

  2. 自定义的迭代器
    list.stream().foreach()会忽略自定义的迭代器,只是在列表上逐个获取元素。list.foreach()会使用自定义的迭代器。

  3. 修改集合
    list.foreach()是快速失败的,遍历的时候操作一旦有问题就会抛异常。而 list.stream().foreach() 则稍后抛异常

  4. 执行顺序
    Collection.forEach()使用集合的迭代器,集合元素的处理顺序是明确的。
    但是Collection.stream.forEach()的处理顺序是不明确的。

Collectors.toList()

获取某一列,例如User类要Id

List<Long> idList = users.stream().map(User::getId).collect(Collectors.toList());

将某一列大写输出

List<String> list1 = Arrays.asList("a","b","c");
List<String> result = list1.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println("大写=" + result);

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-unKKgaRq-1661583418044)(http://apidoc.jadinec.com//server/index.php?s=/api/attachment/visitFile&sign=cd60fa83ce44270dc95bc631a088b7ad)]

Collectors.toMap()

一般用于将List转换为Map

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aJPIJsal-1661583418045)(http://apidoc.jadinec.com//server/index.php?s=/api/attachment/visitFile&sign=3cfd8a049f30fc3f79b45808b0c0aee5)]

参数作用
keyMapper用于指定Key的Function
valueMapper用于指定value的Function
mergeFuncation用于指定多个相同的key如何进行合并的 Funcation

一些常用的方法

  • 将用户的Id和Name作为key和value,存储为Map
Map<Long, String> map = userList.stream().collect(Collectors.toMap(User::getId, User::getName));
  • 当出现相同的key时,取后面的那个
Map<Integer, String> map = userList.stream().collect(Collectors.toMap(User::getAge, User::getName, (a, b) -> b));

Collectors.groupingBy()

分组查询

  • 该返回值是Integer,List 通过年龄进行分组
Map<Integer, List<User>> map = userList.stream().collect(Collectors.groupingBy(User::getAge));

stream().filter

//筛选只要字符串是b的
List<String> list2 = list1.stream().filter(a -> a.equals("b")).collect(Collectors.toList());
System.out.println("list2"  + list2);

结果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uDpgcaM7-1661583418045)(http://apidoc.jadinec.com//server/index.php?s=/api/attachment/visitFile&sign=6a092cbe9617918b113a3abb2923140c)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值