在Java中,除了原始类型,几乎所有东西都是对象。但是你可以使用
functional interfaces来处理
函数。
在Java 8之前,已经有使用情况,通过实例化匿名类经常使用功能接口:
如果您想将函数作为参数传递,有许多表达方式:
假设您想要应用某些函数(例如平方一个值),如果满足一些条件(例如这是一个偶数),则可以使用以下方法:
static Function<Integer, Integer> square = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer t) {
return t*t;
}
};
static Predicate<Integer> isEven = new Predicate<Integer>() {
@Override
public boolean test(Integer t) {
return (t % 2) == 0;
}
};
public static <T, R> void printIf(Predicate<T> pred, Function<T, R> xtrans, List<T> xs) {
for (T x : xs) {
if (pred.test(x)) {
System.out.print(xtrans.apply(x));
System.out.print(" ");
}
}
}
你可以进行测试:
public static void main(String[] args) {
List<Integer> ints = IntStream.range(0, 10)
.boxed()
.collect(Collectors.toList());
printIf(isEven, square, ints);
}
=> 0 4 16 36 64
而且这也可以用lambda表达式来写:
public static void main(String[] args) {
List<Integer> ints = IntStream.range(0, 10).boxed().collect(Collectors.toList());
Predicate<Integer> even = x -> (x % 2) == 0;
Function<Integer, Integer> square = x -> x*x;
printIf(even, square, ints);
}
或者直接:
printIf(x -> (x
而且,您还可以将成员方法用作函数,只要它们具有功能接口签名。
public class Foo {
static Random gen = new Random();
int bar = gen.nextInt(10);
public void println() { System.out.println(bar); }
public int getBar() { return bar; }
}
public static <T> void doToIf(Predicate<T> pred, Consumer<T> doTo, T x) {
if (pred.test(x)) {
doTo.accept(x);
}
}
在一个包含10个 Foo 对象的列表上进行测试:
public static void main(String[] args) {
List<Foo> foos = IntStream.range(0, 10)
.mapToObj(i -> new Foo())
.collect(Collectors.toList());
for (Foo foo : foos) {
doToIf((Foo x) -> x.getBar() % 2 == 0, Foo::println, foo);
}
}
= > 6
2
0
0
4
可以简写为:
public static void main(String[] args) {
IntStream.range(0, 10)
.mapToObj(i -> new Foo())
.filter((Foo x) -> x.getBar() % 2 == 0)
.forEach(Foo::println);
}
boolean
和一个Runnable
。 - Paul Boddington