Built-in Functional Interfaces
Built-in Functional Interfaces就是几种实用的函数式接口,这里介绍几种实用的几种函数式接口,Lambda。
Predicates
Predicates是一个判断函数式接口,示例如下;
Predicate<String> isALongWord = new Predicate<String>() {
@Override
public boolean test(String t) {
return t.length() > 10;
}
};
String s = "successfully"
boolean result = isALongWord.test(s);
Lambda表达式:
Predicate<String> isALongWord = t -> t.length() > 10;
String s = "successfully"
boolean result = isALongWord.test(s);
Predicates也可以被用来过滤接口:
public class Test {
public static void main(String[] args) {
List<String> l = new ArrayList<>();
l.add("successfully");
l.add("easy");
l.add("fortune");
List<String> filtered = l.stream().filter( s -> s.length() > 5 ).collect(Collectors.<String>toList());
System.out.println(filtered);
}
}
filter()方法的参数就是Predicates。
输出结果:
successfully
fortune
Consumer
Consumer是一个接受一个参数但是没有返回值的函数式接口,示例如下:
class Product {
private double price = 0.0;
public void setPrice(double price) {
this.price = price;
}
public void printPrice() {
System.out.println(price);
}
}
public class Test {
public static void main(String[] args) {
Consumer<Product> updatePrice = p -> p.setPrice(5.9);
Product p = new Product();
updatePrice.accept(p);
p.printPrice();
}
}
输出结果:
5.9
Function
Function是一个接受一个参数返回一个结果的函数式接口,通常用来转换值对象,示例如下:
public class Test {
public static void main(String[] args) {
int n = 5;
modifyTheValue(n, val-> val + 10);
modifyTheValue(n, val-> val * 100);
}
static void modifyValue(int v, Function<Integer, Integer> function){
int result = function.apply(v);
System.out.println(newValue);
}
}
输入参数类型和返回值类型可以相同也可以不同。
Supplier
Supplier和Consumer刚好相反,没有输入参数,但有返回值,示例如下:
public class Program {
public static void main(String[] args) {
int n = 3;
display(() -> n + 10);
display(() -> n + 100);
}
static void display(Supplier<Integer> arg) {
System.out.println(arg.get());
}
}
输出结果:
13
103
用于私有类型的函数式接口
上面的函数式接口也有输入私有类型,但有专门处理私有类型的函数式接口,比如:
Predicate<Integer> p = i -> i > 10;
你可以这样用:
IntPredicate p = i -> i > 10;
IntPredicate只能处理int类型数据,所以还有LongPredicate和DoublePredicate。当然还有上面的其它函数式接口也存在对应的私有类型,这里就不一一举例了。