Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: JM Brun
Added: Mar 29, 2018 11:53 AM
Views: 16
Method Reference
  1. // https://www.codementor.io/eh3rrera/using-java-8-method-reference-du10866vx
  2. // Instead of using
  3. // AN ANONYMOUS CLASS
  4. // you can use
  5. // A LAMBDA EXPRESSION
  6. // And if this just calls one method, you can use
  7. // A METHOD REFERENCE
  8.  
  9. // 4 four types of method references:
  10. // A method reference to a static method.
  11. // A method reference to an instance method of an object of a particular type.
  12. // A method reference to an instance method of an existing object.
  13. // A method reference to a constructor.
  14.  
  15. class Numbers {
  16.   public static boolean isMoreThanFifty(int n1, int n2) {
  17.     return (n1 + n2) > 50;
  18.   }
  19.   public static List<Integer> findNumbers(
  20.     List<Integer> l, BiPredicate<Integer, Integer> p) {
  21.       List<Integer> newList = new ArrayList<>();
  22.       for(Integer i : l) {
  23.         if(p.test(i, i + 10)) {
  24.           newList.add(i);
  25.         }
  26.       }
  27.       return newList;
  28.   }
  29. }
  30.  
  31. List<Integer> list = Arrays.asList(12,5,45,18,33,24,40);
  32.  
  33. // Using an anonymous class
  34. findNumbers(list, new BiPredicate<Integer, Integer>() {
  35.   public boolean test(Integer i1, Integer i2) {
  36.     return Numbers.isMoreThanFifty(i1, i2);
  37.   }
  38. });
  39.  
  40. // Using a lambda expression
  41. findNumbers(list, (i1, i2) -> Numbers.isMoreThanFifty(i1, i2));
  42.  
  43. // Using a method reference
  44. findNumbers(list, Numbers::isMoreThanFifty);
  45.