Skip to content

Commit 21195c2

Browse files
add Java Consumer examples
1 parent 0022483 commit 21195c2

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package javaConsumerInterfaceExamples;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
import java.util.function.Consumer;
6+
7+
public class ConsumerInterfaceExample {
8+
static void printMessage(String name) {
9+
System.out.println("Hello " + name);
10+
}
11+
12+
static void printValue(int val) {
13+
System.out.println(val);
14+
}
15+
16+
static void addList(List<Integer> list) {
17+
// Return sum of list values
18+
int result = list.stream()
19+
.mapToInt(Integer::intValue)
20+
.sum();
21+
System.out.println("Sum of list values: " + result);
22+
}
23+
24+
public static void main(String[] args) {
25+
// Referring method to String type Consumer interface
26+
Consumer<String> consumer1 = ConsumerInterfaceExample::printMessage;
27+
consumer1.accept("John"); // Calling Consumer method
28+
// Referring method to Integer type Consumer interface
29+
Consumer<Integer> consumer2 = ConsumerInterfaceExample::printValue;
30+
consumer2.accept(12); // Calling Consumer method
31+
32+
// Creating a list and adding values
33+
List<Integer> list = new ArrayList<>();
34+
list.add(10);
35+
list.add(20);
36+
list.add(30);
37+
list.add(40);
38+
// Referring method to String type Consumer interface
39+
Consumer<List<Integer>> consumer = ConsumerInterfaceExample::addList;
40+
consumer.accept(list); // Calling Consumer method
41+
}
42+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package javaConsumerInterfaceExamples;
2+
3+
import java.util.function.Consumer;
4+
5+
public class MainApp {
6+
public static void main(String... args) {
7+
Consumer<String> print = x -> System.out.println(x);
8+
print.accept("java 8 consumer interface"); // java
9+
}
10+
}

0 commit comments

Comments
 (0)