Consumer Function Interface Example
- java.util.function.Consumer<T> interface has one abstract method called accept(T t).
- Method takes an object of generic type T and it returns nothing (void).
- One can use this interface when there is aneed to access an object of type T and perform some operations on the passed object.
- For example,just look following code
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ConsumerFlight {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11);
Consumer<Integer> consumer = (i)->{System.out.println(i*i);};
makeItSquare(numbers, consumer);
}
public static <T> void makeItSquare(List<T> list, Consumer<T> consumer) {
for(T t : list) {
consumer.accept(t);
}
}
}
Output
1
4
9
16
25
36
49
64
81
100
121
import java.util.List;
import java.util.function.Consumer;
public class ConsumerFlight {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11);
Consumer<Integer> consumer = (i)->{System.out.println(i*i);};
makeItSquare(numbers, consumer);
}
public static <T> void makeItSquare(List<T> list, Consumer<T> consumer) {
for(T t : list) {
consumer.accept(t);
}
}
}
Output
1
4
9
16
25
36
49
64
81
100
121