JDK lambda表达式

JDK lambda表达式

基本使用方法

1. 无参,如定义一个线程,可以简写为

 new Thread(() -> System.out.print("运行")).start();

2. 有参数

Collections.sort(list, (o1, o2) -> return o1.compareTo(o2));

3. 类型改变 && 方法调用

public class Demo {
    
    @Test
    public void test02() {
        List<Integer> intList = new ArrayList<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        intList.add(4);

        // List<Integer>转List<String>
        List<String> stringList = intList.stream().map(x -> String.valueOf(x)).collect(Collectors.toList());
        
        // 调用打印
        stringList.forEach(System.out::println);     
    }
  }

4. List转Map

public class Demo {
    @Test
    public void test03() {
        List<Integer> intList = new ArrayList<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        intList.add(4);

        Map<Integer, String> stringMap = intList.stream().collect(Collectors.toMap(x -> x, x -> "数据为:" + String.valueOf(x)));

        stringMap.entrySet().forEach(x-> System.out.println(x.getKey() + "\t" + x.getValue()));
    }
}

5. Filter

public class Demo {
    @Test
    public void test03() {
        List<Integer> intList = new ArrayList<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        intList.add(4);

        // 过滤,只要大于2的数据
        Map<Integer, String> stringMap = intList.stream().filter(x -> x > 2 ).collect(Collectors.toMap(x -> x, x -> "数据为:" + String.valueOf(x)));

        stringMap.entrySet().forEach(x-> System.out.println(x.getKey() + "\t" + x.getValue()));
    }
}

6. groupBy

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: pp_lan
 * @date: 2021/8/27 7:37
 */
public class DemoTest {

    @Test
    public void test04() {
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "力宏"));
        userList.add(new User(2, "张力"));
        userList.add(new User(1, "虚仓"));
        userList.add(new User(3, "君太"));

        // 根据groupId分组
        Map<Integer, List<User>> collect = userList.stream().collect(Collectors.groupingBy(x -> x.getGroupId()));

        collect.entrySet().forEach(x -> System.out.println("组: " + x.getKey() + "\t成员:" + x.getValue()));
    }

    public class User {
        private Integer groupId;

        private String name;

        public User(Integer id, String name) {
            this.groupId = id;
            this.name = name;
        }

        public Integer getGroupId() {
            return groupId;
        }

        public void setGroupId(Integer groupId) {
            this.groupId = groupId;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "groupId=" + groupId +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
}

7. Predicate

public class DemoTest {
    
    @Test
    public void test05() {
        List<Integer> intList = new ArrayList<>();
        intList.add(1);
        intList.add(2);
        intList.add(3);
        intList.add(4);

        // 偶数
        Predicate<Integer> predicate = (n) -> n % 2 == 0;

        intList.forEach(x -> {
            if(predicate.test(x)) {
                System.out.println("偶数:" + x);
            }
        });
    }
}

8. @FunctionalInterface

public class DemoTest {
    @Test
    public void test06() {
        List<Worker> workers = new ArrayList<>();
        workers.add(()-> {
            System.out.println("打工1");
        });
        workers.add(()-> {
            System.out.println("打工2");
        });
        workers.add(()-> {
            System.out.println("打工3");
        });

        workers.forEach(Worker::work);
    }

    @FunctionalInterface
    public interface Worker {

        /**
         * 工作
         */
        void work();
    }
}
JDK 1.8 中引入了 Lambda 表达式,它是一种简洁而强大的编程语法,用于支持函数式编程。Lambda 表达式可以用来替代一些需要使用匿名内部类的情况,并提供了更简洁的语法来定义函数式接口的实现。 Lambda 表达式的基本语法如下: ```java (parameters) -> { body } ``` 其中,parameters 是参数列表,可以为空或包含一个或多个参数,多个参数之间使用逗号分隔。body 是 Lambda 表达式的主体,可以是一个表达式或一段代码块。 下面是一些常见的 Lambda 表达式用法示例: 1. Lambda 表达式作为函数式接口的实现: ```java // 定义一个函数式接口 interface MyInterface { void doSomething(); } // 使用 Lambda 表达式实现函数式接口 MyInterface lambda = () -> { System.out.println("Doing something..."); }; // 调用 Lambda 表达式 lambda.doSomething(); ``` 2. Lambda 表达式作为参数传递给方法: ```java // 定义一个接受函数式接口作为参数的方法 void performAction(MyInterface action) { action.doSomething(); } // 使用 Lambda 表达式作为参数传递 performAction(() -> { System.out.println("Performing action..."); }); ``` 3. Lambda 表达式与集合的结合: ```java List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); // 使用 Lambda 表达式遍历集合 names.forEach(name -> { System.out.println("Hello, " + name); }); ``` Lambda 表达式还支持方法引用、参数类型推断等特性,可以更进一步简化代码。它在函数式编程和并行处理等场景中具有很大的优势。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值