Consumer接口
public void test_consumer(){
List<Integer> list = new ArrayList<Integer>(){
{
add(1);
add(2);
add(3);
add(4);
}
};
// 1. 使用接口实现方法
Consumer<Integer> consumer = new Consumer<Integer>() {
@Override
public void accept(Integer integer) {
System.out.println(integer);
}
};
list.forEach(consumer);
// 2. lambda表达式
list.forEach(i -> System.out.println(i));
// 3. 调用方法
list.forEach(System.out::println);
}
Supplier接口
public void test_supplier(){
// 1. 使用接口实现方法
Supplier<Double> supplier = new Supplier<Double>() {
@Override
public Double get() {
return Math.random() * 10;
}
};
System.out.println(supplier.get());
// 2. lambda表达式
supplier = () -> Math.random() * 10;
System.out.println(supplier.get());
// 3. 方法引用
supplier = Math::random;
System.out.println(supplier.get());
}
Predicate接口
public void test_predicate(){
List<Integer> list = new ArrayList<Integer>(){
{
add(1);
add(2);
add(3);
add(4);
}
};
// 1. 使用接口实现方法
Predicate<Integer> predicate = new Predicate<Integer>() {
@Override
public boolean test(Integer integer) {
return integer > 2;
}
};
list.stream().filter(predicate).forEach(System.out::println);
// 2. lambda表达式
list.stream().filter(i -> i > 2).forEach(System.out::println);
}
Function接口
public void test_function(){
List<String> list = new ArrayList<String>(){
{
add("Harry");
add("Ron");
add("Hermione");
}
};
// 1. 使用接口实现方法
Function<String, Integer> function = new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return s.length();
}
};
list.stream().map(function).forEach(System.out::println);
// 2. lambda表达式
list.stream().map(s -> s.length()).forEach(System.out::println);
// 3. 方法引用
list.stream().map(String::length).forEach(System.out::println);
}
参考:
https://www.cnblogs.com/SIHAIloveYAN/p/11288064.html