四大函数式接口
juf包下的
package com.xrh.juf;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class HanShuShiJieKou {
public static void main(String[] args) {
//1.函数型接口,有输入有输出
//函数型接口--匿名内部类
Function<String ,Integer>function=new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return 123;
}
};
//函数型接口--lambda表达式
Function<String,Integer>function1=(String s)->{ //这里因为只有一个参数,可以不写小括号,类型也可以省略
return 123;
};
System.out.println(function.apply("1"));
//2.断定型接口,有输入,返回值式布尔类型的
Predicate<String>predicate=new Predicate<String>() {
@Override
public boolean test(String s) {
return s.isEmpty();
}
};
Predicate<String>predicate1=(String s)->{
return s.isEmpty();
};
System.out.println(predicate1.test("1"));
//3.消费型接口,有输入,没输出
Consumer<String>consumer=new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
Consumer consumer1=s->{
System.out.println(s);
};
consumer1.accept("1");
//4.供给型接口,返回一个类型的
Supplier<String> supplier=new Supplier<String>() {
@Override
public String get() {
return "123";
}
};
Supplier<String>supplier1=()->{
return "123";
};
System.out.println(supplier.get());
}
}
Stream流式计算
jus包下的
package com.xrh.juf;
import java.util.Arrays;
import java.util.List;
/**
* 按照给出的数据,按照一定的条件返回
* 就相当于一组sql语句,把集合转换成流(数据流)
*
* 题目:
* 找出偶数ID且年龄大于24且用户转换为大写且用户字母名字倒序,输出一个名字
*/
public class StreamTest {
public static void main(String[] args) {
User user1=new User(10,"zhangsan",25);
User user2=new User(12,"lisi",26);
User user3=new User(13,"wangwu",12);
User user4=new User(14,"maliu",22);
User user5=new User(15,"chenqi",25);
List<User>list= Arrays.asList(user1,user2,user3,user4,user5);
list.stream().filter(t->{
return t.getId()%2==0;
}).filter(t->{
return t.getAge()>24;
}).map((s)->{ //map以后装的就是返回的值了
return s.getUserName().toUpperCase();
}).sorted(( o1, o2)->{
return o2.compareTo(o1);
}).limit(1).forEach(System.out::println);
}
}
ForkJoin
异步回调
CompletableFuture
package com.xrh.completablefuture;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CompletableFutureTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> { //新开一个线程,做完就做完了,没有返回值,----》异步
System.out.println(Thread.currentThread().getName() + " 没有返回"); //void的包装类Void
});
System.out.println(completableFuture.get());//这个值是null
CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> { //新开一个线程,有返回值
System.out.println(Thread.currentThread().getName() + " 有返回");
int age=10/0;
return 1024;
});
//BiConsumer这个函数式接口有两个输入参数
//如果上面个这个线程正常执行后,走下面这个分支,如果异常则走
completableFuture2.whenComplete((t,u)->{
System.out.println("t: "+t);
System.out.println("u: "+u);
}).exceptionally(f->{
System.out.println("exception: "+f.getMessage());
return 404;
});
}
}