Lambda 4大内置函数
最近用到了java8的lambda函数,记录一下
Lambda 4大内置函数基本满足需求
- Consumer:消费型接口,内有抽象方法—void accept(T t)
consumer.java 类中有两个方法 accept, andThen.
简单用例
Consumer 消费性接口
/***
* 消费性接口 有参无返回值
* @param money
* @param consumer
*/
public static void consumerPtion(int money, Consumer<Integer> consumer ){
consumer.accept(money);
}
public static void consumerAndThen(List<Employee> list,Consumer<Employee> consumer,Consumer<Employee> employeeConsumer){
for(Employee employee:list){
consumer.andThen(employeeConsumer).accept(employee);
}
}
public static void main(String[] args) {
List<Employee> list = Arrays.asList(
new Employee("张三",26,17896),
new Employee("李四",45,16663),
new Employee("王五",38,5482));
consumerPtion(200,(x)->log.info("消费接口调用,消费:"+x+"元"));
consumerAndThen(list,(employee)-> {
System.out.print("第一组姓名:"+employee.getName()+"," );
},(e)->{
System.out.println("年纪:"+e.getAge()+".");
});
}
- Supplier:供给型接口(供给型),内有抽象方法—T get();
Supplier供给型接口
**
* 无参数 有返回值
*
* @param num 指定生成的数量
* @param supplier 根据num生成 随机数个数
* @return 装有生产好的整数的集合
*/
public static List<Integer> SupplierNumber(int num, Supplier<Integer> supplier){
List<Integer> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
Integer integer = supplier.get();
list.add(integer);
}
return list;
}
/***
* 生成随机数
*/
List<Integer> integerList = SupplierNumber(5,()-> (int)(Math.random()*30));
integerList.stream().forEach(System.out::println);
- Function<T, R>:函数型接口,内有抽象方法—R apply(T t)
Function 函数式接口
/**
* 函数型接口 有参数 有返回值
* @param list 指定需要被处理的对象
* @param fun 自定义处理办法
* @return 处理好的字符串
*/
public static Employee strHandler(List<Employee> list , Function<Employee, Employee> fun){
for(Employee employee : list ){
if("张三".equals(employee.getName())){
return fun.apply(employee);
}
}
return null;
}
public static void main(String[] args) {
List<Employee> list = Arrays.asList(
new Employee("张三",26,17896),
new Employee("李四",45,16663),
new Employee("王五",38,5482));
Employee employee = strHandler(list,(x)-> new Employee("xxxx",x.getAge(),x.getMoney()));
System.out.println(employee);
}
- Predicate:断言型接口,内有抽象方法—boolean test(T t)
Predicate 断言式接口
/***
* 自定义 函数
* @param list
* @param predicate
* @return
*/
public static Employee predicateTest(List<String> list , Predicate<String> predicate){
list.forEach(t->{
if(predicate.test(t)){
System.out.println(t);
}
});
return null;
}
List<String> stringList = Arrays.asList("xxxx","aaa","ffff","wewe");
predicateTest(stringList,(x)->x.equals("aaa"));
简单写几个例子 记录一下。