在Java 8中, Consumer是一个功能接口; 它接受一个参数,但不返回任何内容。
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
1.消费者
Java8Consumer1.java
package com.mkyong.java8;
import java.util.function.Consumer;
public class Java8Consumer1 {
public static void main(String[] args) {
Consumer<String> print = x -> System.out.println(x);
print.accept("java"); // java
}
}
输出量
java
2.高阶函数
2.1此示例接受Consumer
作为参数,模拟forEach
以打印列表中的每个项目。
Java8Consumer2.java
package com.mkyong.java8;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class Java8Consumer2 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
// implementation of the Consumer's accept methods.
Consumer<Integer> consumer = (Integer x) -> System.out.println(x);
forEach(list, consumer);
// or call this directly
forEach(list, (Integer x) -> System.out.println(x));
}
static <T> void forEach(List<T> list, Consumer<T> consumer) {
for (T t : list) {
consumer.accept(t);
}
}
}
输出量
1
2
3
4
5
1
2
3
4
5
2.2相同的forEach
方法,以接受Consumer
作为参数; 这次,我们将打印字符串的长度。
Java8Consumer3.java
package com.mkyong.java8;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class Java8Consumer3 {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "ab", "abc");
forEach(list, (String x) -> System.out.println(x.length()));
}
static <T> void forEach(List<T> list, Consumer<T> consumer) {
for (T t : list) {
consumer.accept(t);
}
}
}
输出量
1
2
3
看到了灵活性吗?