Java1.8新特性 - Java内置的四大核心函数式接口
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java1.8新特性 - Java内置的四大核心函数式接口,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1668字,纯文字阅读大概需要3分钟。
内容图文
Java内置的四大核心函数式接口
Consumer:消费型接口
对类型为T的对象应用操作,包含方法:void accept(T t)
public class TestLambda02 {
public static void main(String[] args) {
testConsumer(9999, (x) -> {
System.out.println("打游戏花费:" + x);
});
}
public static void testConsumer(double money, Consumer<Double> consumer) {
consumer.accept(money);
}
}
Supplier:供给型接口
返回包含类型为T的对象,包含方法:T get()
public class TestLambda02 {
public static void main(String[] args) {
List<Integer> list = testSupplier(10, () -> (int)(Math.random() * 100));
list.forEach(System.out::println);
}
public static List<Integer> testSupplier(int num, Supplier<Integer> supplier) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < num; i ++) {
Integer n = supplier.get();
list.add(n);
}
return list;
}
}
Function<T, R>:函数型接口
对类型为T的对象应用操作,并返回结果,结果类型为R。包含方法:R apply(T t)
public class TestLambda02 {
public static void main(String[] args) {
String string = testFunction("哈哈哈哈哈哈哈", (str) -> str.substring(0, str.length() - 2));
System.out.println("---->" + string);
}
public static String testFunction(String str, Function<String, String> function) {
return function.apply(str);
}
}
Predicate(T):断定型接口
确定类型为T的对象是否满足某约束,并返回boolean值。包含方法:boolean test(T t)
public class TestLambda02 {
public static void main(String[] args) {
System.out.println(testPredicate("哈哈哈哈皇后", (str) -> str.length() == 3));
}
public static boolean testPredicate(String string, Predicate<String> predicate) {
return predicate.test(string);
}
}
PS:除了这四个接口,java还内置了其他很多接口,这里不再赘述。可以在rt.jar文件下的java/util/function包下查看。
原文:https://www.cnblogs.com/fx-blog/p/11743909.html
内容总结
以上是互联网集市为您收集整理的Java1.8新特性 - Java内置的四大核心函数式接口全部内容,希望文章能够帮你解决Java1.8新特性 - Java内置的四大核心函数式接口所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。