Java 8中新接口的使用示例
下文笔者讲述java8中,Consumer接口的功能简介说明,如下所示
Java8Consumer2.java
Consumer接口的功能
接收参数,但不返回任何内容
Consumer接口的源码
@FunctionalInterface public interface Consumer<T> { void accept(T t); }Java8Consumer1.java
package com.java265.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爱好者"); } }例2:Consumer作为参数,打印列表中元素
Java8Consumer2.java
package com.java265.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(22,44,55,77,88,120); Consumer<Integer> consumer = (Integer x) -> System.out.println(x); forEach(list, consumer); 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); } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。