@@ -52,5 +52,42 @@ void accept(T t);
52
52
default Consumer<T> andThen(Consumer<? super T> after);
53
53
```
54
54
- The ``` accept ``` method is the Single Abstract Method (SAM) which accepts a single argument of type T.
55
- - ``` andThen ``` is a default method used for composition.
55
+ - ``` andThen ``` is a default method used for composition or chaining.
56
+ - ``` andThen ``` takes a consumer as input and returns a consumer.
57
+
58
+ #### ``` accept ``` method example
59
+
60
+
61
+ ```
62
+ public static void printUsingAcceptMethod(){
63
+ // Create a function that prints what ever is passed through accept method of consumer interface.
64
+ Consumer<String> printConsumer = t -> System.out.println(t);
65
+ Stream<String> cities = Stream.of("Sydney", "Dhaka", "New York", "London");
66
+ // foreach method of stream interface takes a consumer through parameter.
67
+ cities.forEach(printConsumer);
68
+ }
69
+
70
+ ```
71
+
72
+ ### ``` andThen ``` method example.
73
+
74
+ ```
75
+ public void printUsingAndTherMethod(){
76
+ List<String> cities = Arrays.asList("Sydney", "Dhaka", "New York", "London");
77
+
78
+ // This consumer converts an string list into upper case.
79
+ Consumer<List<String>> upperCaseConsumer = list -> {
80
+ for(int i=0; i< list.size(); i++){
81
+ list.set(i, list.get(i).toUpperCase());
82
+ }
83
+ };
84
+
85
+ // This Consumer print list of string
86
+ Consumer<List<String>> printConsumer = list -> list.stream().forEach(System.out::println);
87
+
88
+ // Chaining consumers using andThen
89
+ upperCaseConsumer.andThen(printConsumer).accept(cities);
90
+ }
91
+
92
+ ```
56
93
0 commit comments