1. Function接口

  1. /**
  2. * function 接口测试
  3. * function 函数只能接受一个参数,要接受两个参数,得使用BiFunction接口
  4. */
  5. public class FunctionTest {
  6. @Test
  7. public void Test (){
  8. FunctionTest test = new FunctionTest();
  9. // System.out.println(test.compute(4, x->x*2));
  10. System.out.println(test.compute(2, v -> v * 3, v -> v * v));
  11. System.out.println(test.compute2(2, v -> v * 3, v -> v * v));
  12. System.out.println(test.compute3(2,3, (a, b)-> a+b));
  13. System.out.println(test.compute4(2, 3, (a, b) -> a + b, a -> a * a));
  14. }
  15. /**
  16. * function的第一个参数是输入, 第二个参数是输出
  17. * @param a
  18. * @param function
  19. * @return
  20. */
  21. public int compute(int a, Function<Integer, Integer> function) {
  22. int result = function.apply(a);
  23. return result;
  24. }
  25. /**
  26. * compose 组合, 先执行传入的参数方法,再执行本身的方法
  27. * @param a 输入
  28. * @param func1 本身方法
  29. * @param func2 传入的参数方法
  30. * @return
  31. */
  32. public int compute(int a, Function<Integer, Integer> func1, Function<Integer, Integer> func2) {
  33. return func1.compose(func2).apply(a);
  34. }
  35. /**
  36. * andThen 方法,先执行自己的方法,再执行传入的参数方法
  37. * @param a
  38. * @param func1 本身方法
  39. * @param func2 传入的参数方法
  40. * @return
  41. */
  42. public int compute2(int a, Function<Integer, Integer> func1, Function<Integer, Integer> func2) {
  43. return func1.andThen(func2).apply(a);
  44. }
  45. /**
  46. * biFunction接口可传入两个参数
  47. * @param a
  48. * @param b
  49. * @param biFunction
  50. * @return
  51. */
  52. public int compute3(int a, int b, BiFunction<Integer, Integer, Integer> biFunction) {
  53. return biFunction.apply(a, b);
  54. }
  55. /**
  56. * biFunction只有一个andThen方法(参数还是Function),因为他只返回一个值,不能返回两个值
  57. * @param a
  58. * @param b
  59. * @param biFunction
  60. * @param function
  61. * @return
  62. */
  63. public int compute4(int a, int b, BiFunction<Integer, Integer, Integer> biFunction, Function<Integer, Integer> function) {
  64. return biFunction.andThen(function).apply(a,b);
  65. }
  66. }
  1. // 模仿Function接口, 接受一个参数, 返回一个值
  2. @FunctionalInterface
  3. interface FakeInterface<J, R> {
  4. R fuck(J t);
  5. }
  6. public class MyTest {
  7. public String myTest(Integer a, FakeInterface<Integer, String> fakeInterface) {
  8. System.out.println("执行我的fakeInterface中的方法, 传入一个参数");
  9. String s = fakeInterface.fuck(a);
  10. return s;
  11. }
  12. public static void main(String[] args) {
  13. MyTest myTest = new MyTest();
  14. String s = myTest.myTest(5, x -> String.valueOf(x));
  15. System.out.println(s);
  16. }
  17. }

2. BiFunction接口

  1. public class PersonTest {
  2. @Test
  3. public void test1() {
  4. Person p1 = new Person("zhangsan", 20);
  5. Person p2 = new Person("lisi", 30);
  6. Person p3 = new Person("wangwu", 40);
  7. List<Person> persons = Arrays.asList(p1, p2, p3);
  8. PersonTest test = new PersonTest();
  9. List<Person> result = test.getPersonByAge(30, persons);
  10. result.forEach(x-> System.out.println(x.getUsername()));
  11. }
  12. @Test
  13. public void test2() {
  14. Person p1 = new Person("zhangsan", 20);
  15. Person p2 = new Person("lisi", 30);
  16. Person p3 = new Person("wangwu", 40);
  17. List<Person> persons = Arrays.asList(p1, p2, p3);
  18. PersonTest test = new PersonTest();
  19. List<Person> result = test.getPersonByAge2(30, persons, (age, personList) -> {
  20. return personList.stream().filter(p->p.getAge() > age).collect(Collectors.toList());
  21. });
  22. result.forEach(x-> System.out.println(x.getUsername()));
  23. }
  24. /**
  25. * 强行使用lamboda来写代码
  26. * @param age
  27. * @param persons
  28. * @return
  29. */
  30. public List<Person> getPersonByAge(int age, List<Person> persons) {
  31. // 定义函数操作
  32. BiFunction<Integer, List<Person>, List<Person>> biFunction =
  33. (ageOfPerson, personList) ->
  34. personList.stream().filter(person -> person.getAge()> ageOfPerson).collect(Collectors.toList());
  35. // 执行函数操作
  36. return biFunction.apply(age, persons);
  37. }
  38. /**
  39. * 不预先定义函数操作
  40. * @param age
  41. * @param persons
  42. * @param biFunction 函数操作由用户传入,更加灵活
  43. * @return
  44. */
  45. public List<Person> getPersonByAge2(int age, List<Person> persons, BiFunction<Integer, List<Person>, List<Person>> biFunction) {
  46. // 执行函数操作
  47. return biFunction.apply(age, persons);
  48. }

3. Predicate接口

  1. import java.util.Arrays;
  2. import java.util.List;
  3. import java.util.function.Predicate;
  4. /**
  5. * predicate接口, 是一个根据给定参数来决定返回bool值的判断式函数式接口
  6. */
  7. public class PredicateTest {
  8. @Test
  9. public void Test1() {
  10. Predicate<String> predicate = p->p.length() > 5;
  11. System.out.println(predicate.test("hello"));
  12. }
  13. // 接口的简单练习
  14. @Test
  15. public void Test2() {
  16. List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
  17. PredicateTest predicateTest = new PredicateTest();
  18. System.out.println("打印出偶数: ");
  19. predicateTest.conditionFilter(list, item->(item & 1) == 0);
  20. System.out.println("---------------------------");
  21. System.out.println("打印出奇数: ");
  22. predicateTest.conditionFilter(list, item->(item & 1) == 1);
  23. System.out.println("---------------------------");
  24. predicateTest.conditionFilter(list, x->true);
  25. System.out.println("----------------------------");
  26. System.out.println("打印:, 大于5,并且偶数: ");
  27. predicateTest.conditionAndFilter(list, x -> x > 5, x -> (x & 1) == 0);
  28. System.out.println("----------------------------");
  29. }
  30. /**
  31. * 函数式编程的一大特点就是将行为提到方法外面,由用户传入
  32. * 调用时动态传入动作,更高层次的抽象化
  33. * @param list
  34. * @param predicate
  35. */
  36. public void conditionFilter(List<Integer> list, Predicate<Integer> predicate) {
  37. // 将通过条件判断的数字打印出来
  38. for (Integer i : list) {
  39. if (predicate.test(i)) {
  40. System.out.println(i);
  41. }
  42. }
  43. }
  44. /**
  45. * predicate接口的 与 运算, 打印出符合两个条件的结果
  46. 同理, 可理解predict中的其他逻辑运算
  47. * @param list
  48. * @param p1
  49. * @param p2
  50. */
  51. public void conditionAndFilter(List<Integer> list, Predicate<Integer> p1, Predicate<Integer> p2) {
  52. for (Integer i : list) {
  53. if (p1.and(p2).test(i)) {
  54. System.out.println(i);
  55. }
  56. }
  57. }
  58. /**
  59. * Predicate.isEqual() 方法用于判断两个参数是否相同, 依据就是 Objects#equals(Object, Object)}.
  60. * 这个方法不怎么好理解, 说白了,就是调用传入参数的equals方法,
  61. * 得到其方法的引用,而这个引用又刚好符合Predict函数的格式,可以作为Predict来使用
  62. * @param object
  63. * @return
  64. */
  65. public Predicate<String> isEqual(Object object) {
  66. return Predicate.isEqual(object);
  67. }
  68. @Test
  69. public void Test3() {
  70. PredicateTest predicateTest = new PredicateTest();
  71. System.out.println(predicateTest.isEqual("test").test("test")); // true
  72. System.out.println(predicateTest.isEqual("test").test("test2")); // false
  73. System.out.println(predicateTest.isEqual(null).test("test")); // false
  74. System.out.println(predicateTest.isEqual(null).test(null)); //true
  75. }
  76. }

4. Supplier接口

  1. @Data
  2. public class Student {
  3. private String name = "zhangsan";
  4. private Integer age = 20;
  5. }
  6. /**
  7. * Supplier接口, 不接受参数, 返回一个结果
  8. * 常用于 工厂
  9. *
  10. */
  11. public class SupplierTest {
  12. // 最简单例子
  13. @Test
  14. public void Test() {
  15. Supplier<String> supplier = () -> "hello world";
  16. System.out.println(supplier.get());
  17. }
  18. /**
  19. * 利用supplier生产学生
  20. */
  21. @Test
  22. public void Test2() {
  23. Supplier<Student> supplier = ()->new Student();
  24. System.out.println(supplier.get().toString());
  25. // 更进一步, 调用Student的构造方法, 叫做构造方法的引用
  26. // 不接受参数, 返回Student对象,符合函数式接口的要求
  27. // 编译器会去Student找不带参数, 返回Student的构造方法
  28. Supplier<Student> supplier2 = Student::new;
  29. System.out.println(supplier2.get().toString());
  30. }
  31. }

5. Consumer接口

接收一个参数, 不返回值, 但可能改变传入的参数,通过这个改变的副作用来实现业务,list.forEach中就是一个Consumer接口作为参数

  1. list.forEach(x->System.out.println(x));
  2. default void forEach(Consumer<? super T> action) {
  3. Objects.requireNonNull(action);
  4. for (T t : this) {
  5. action.accept(t);
  6. }
  7. }
  1. public class MyTest {
  2. public void myTest2(Integer a, Consumer<Integer> consumer) {
  3. consumer.accept(a);
  4. }
  5. public static void main(String[] args) {
  6. MyTest myTest = new MyTest();
  7. myTest.myTest2(5, x-> {
  8. System.out.println("可以操作x,但没有返回值");
  9. });
  10. }
  11. }

jdk8中几个核心的函数式接口笔记的更多相关文章

  1. 乐字节-Java8核心特性实战之函数式接口

    什么时候可以使用Lambda?通常Lambda表达式是用在函数式接口上使用的.从Java8开始引入了函数式接口,其说明比较简单:函数式接口(Functional Interface)就是一个有且仅有一 ...

  2. Java8内置的四大核心函数式接口

    package java_8; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import j ...

  3. Java8新特性(一)——Lambda表达式与函数式接口

    一.Java8新特性概述 1.Lambda 表达式 2. 函数式接口 3. 方法引用与构造器引用 4. Stream API 5. 接口中的默认方法与静态方法 6. 新时间日期 API 7. 其他新特 ...

  4. Java 8 特性 —— 函数式接口

    函数式接口 概述:接口中只有一个抽象方法. 函数式接口,即适用于函数式编程场景的接口.而 Java 中的函数式编程体现就是 Lambda,所以函数式接口就是可以适用于 Lambda 使用的接口.只有确 ...

  5. JAVA8之函数式接口

    由于JDK8已经发布一段时间了,也开始逐渐稳定,未来使用JAVA语言开发的系统会逐渐升级到JDK8,因为为了以后工作需要,我们有必要了解JAVA8的一些新的特性.JAVA8相对JAVA7最重要的一个突 ...

  6. Java8 新特性 函数式接口

    什么是函数式接口   函数式接口是Java8引用的一个新特性,是一种特殊的接口:SAM类型的接口(Single Abstract Method).但是它还是一个接口,只是有些特殊罢了.  函数式接口的 ...

  7. java8学习之Supplier与函数式接口总结

    Supplier接口: 继续学习一个新的函数式接口--Supplier,它的中文意思为供应商.提供者,下面看一下它的javadoc: 而具体的方法也是相当的简单,就是不接受任何参数,返回一个结果: 对 ...

  8. JDK8中Stream使用解析

    JDK8中Stream使用解析 现在谈及JDK8的新特新,已经说不上新了.本篇介绍的就是Stream和Lambda,说的Stream可不是JDK中的IO流,这里的Stream指的是处理集合的抽象概念『 ...

  9. Java8 函数式接口 @FunctionalInterface以及常用Consumer<T>、Supplier<T>、Function<T, R>、Predicate<T>总结

    首先看看什么是Lambda 表达式 Lambda是一个匿名函数,我们可以把Lambda表达式理解为一段可以传递的代码(将代码像数据一样传递):最简单的Lambda表达式可由逗号分隔的参数列表.-> ...

随机推荐

  1. asp.net ajax传递Json给aspx.cs后台 webmethod方法传递json

    1.提取一个向后台写入数据的方法 ///向后台cs页面请求数据的方法 function myPost(url,data,func) { $.ajax({ type: "post", ...

  2. go语言系列--输出正弦函数

    实验所用到的标准库和包 库与包之间的理解可以类比成:数据库种的库和表 库名 作用 image 常见图形格式的访问及生成 log 日志记录库 math 数学库 os 操作系统平台不依赖平台操作封装 查看 ...

  3. BZOJ 1022 Luogu P4279 [SHOI2008]小约翰的游戏 (博弈论)

    题目链接: (bzoj) https://www.lydsy.com/JudgeOnline/problem.php?id=1022 (luogu) https://www.luogu.org/pro ...

  4. [BZOJ3796]Mushroom追妹纸:后缀自动机+KMP

    分析 这道题有个\(O(n)\)的后缀自动机做法,感觉很好理解就在这说一下. 先对\(s1\)和\(s2\)求最长公共子串,对于\(s2\)的每一个下标\(i\),求一个\(f[i]\)表示以\(s2 ...

  5. sqli-labs(31)

    0x01找闭合 这里是WAF的jsp调到php的同样 第二个参数构造 偷看源码 闭合是") 我们尝试一下构造爆破数据库名 login.php?id=&id=-") unio ...

  6. [LeetCode]-011-Longest Common Prefix

    Write a function to find the longest common prefix string amongst an array of strings. []=>" ...

  7. 第一次试验报告&学习总结

    打印输出所有的"水仙花数",所谓"水仙花数"是指一个3位数,其中各位数字立方和等于该数本身.例如,153是一个"水仙花数". 试验代码: p ...

  8. Python的 counter内置函数,统计文本中的单词数量

    counter是 colletions内的一个类 可以理解为一个简单的计数 import collections str1=['a','a','b','d'] m=collections.Counte ...

  9. 【linux】的文件按时间排序

    > ls -alt # 按修改时间排序 > ls --sort=time -la # 等价于> ls -alt > ls -alc # 按创建时间排序 > ls -alu ...

  10. symbol,iterator,generator

    1.symbol是在ES6中引入的一种基本数据类型,因为symbol是不重复.唯一的数据特性,symbol设计是被用来表示对象内部的私有属性的.     symbol.for与symbol.keyfo ...