Java 8 : Method as Argument (Behavior parameterization)



Behavior parameterization is about to take multiple different behaviors as parameters and use them to complete different behaviors. Behavior parameterization allows you make your code more flexible to the changing requirements of customer and saves on developers efforts in the future requirements. Here we are passing behaviour as a parameter in a method. There are two ways you can pass behaviour as parameter.
1) Using lamda expression 
2) Using method reference (ClassName::methodName) 

Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.util.ArrayList;
import java.util.List;

interface Function < T > {
 boolean test(T t);
}

class Apple {
 private String id;
 private String color;
 private String size;
 Apple(String id, String color, String size) {
  this.id = id;
  this.color = color;
  this.size = size;
 }
 public String getId() {
  return id;
 }
 public String getColor() {
  return color;
 }
 public String getSize() {
  return size;
 }
 @Override
 public String toString() {
  return "Apple [id=" + id + ", color=" + color + ", size=" + size + "]";
 }
}

class AppleFarm {
 public static boolean isRedApple(Apple apple) {
  return "red".equalsIgnoreCase((apple.getColor()));
 }
 public static boolean isSmallApple(Apple apple) {
  return "small".equalsIgnoreCase(apple.getSize());
 }
 public List < Apple > filterApples(List < Apple > apples, Function < Apple > predicate) {
  List < Apple > filteredApplesList = new ArrayList < Apple > ();
  for (Apple apple: apples) {
   if (predicate.test(apple)) {
    filteredApplesList.add(apple);
   }
  }
  return filteredApplesList;
 }
}

public class FunctionInArgumentFlight {
 public static void main(String[] args) {
  Apple a1 = new Apple("1", "red", "small");
  Apple a2 = new Apple("2", "red", "big");
  Apple a3 = new Apple("3", "green", "small");
  Apple a4 = new Apple("4", "yellow", "small");

  List < Apple > appleStore = new ArrayList < Apple > ();
  appleStore.add(a1);
  appleStore.add(a2);
  appleStore.add(a3);
  appleStore.add(a4);

  System.out.println("RED APPLES");
  AppleFarm appleFarm = new AppleFarm();
  List < Apple > redApples = appleFarm.filterApples(appleStore, AppleFarm::isRedApple);
  display(redApples);

  System.out.println("\nSMALL APPLES");
  List < Apple > smallApples = appleFarm.filterApples(appleStore, AppleFarm::isSmallApple);
  display(smallApples);

  System.out.println("\nBIG APPLES");
  List < Apple > bigApples = appleFarm.filterApples(appleStore, (Apple a) -> "big".equalsIgnoreCase(a.getSize()));
  display(bigApples);
 }

 public static void display(List < Apple > apples) {
  for (Apple apple: apples) {
   System.out.println(apple);
  }
 }
}