Consumer and Bi-consumer functional interface java
Functional Interface:
Functional interface is an interface that contains only one abstract method. A functional interface can have any number of default methods.
Consumer, Bi-consumer, Runnable are some example of functional interface. Annotation @FunctionalInterface is not mandatory however @FunctionalInterface annotation is used to ensure that the functional interface can’t have more than one abstract method
Consumer, Bi-consumer, Runnable are some example of functional interface. Annotation @FunctionalInterface is not mandatory however @FunctionalInterface annotation is used to ensure that the functional interface can’t have more than one abstract method
Consumer :
@FunctionalInterface
public interface Consumer < T > {
void accept(T t);
}
public class ConsumerImpl {
public static void main(String args[]) {
List<String> strList = Arrays.asList("one","two","three");
strList.forEach(new Consumer<String>() {
@Override
public void accept(String str) {
System.out.println(str);
}
});
}
}
OR Lambda format
java.lang.Iterable.forEach() method internally uses Consumer interface.
public class ConsumerImpl {
public static void main(String args[]) {
List<String> strList = Arrays.asList("one","two","three");
strList.forEach(x->System.out.println(x));
}
}
Bi-Consumer :
@FunctionalInterface
public interface BiConsumer<T, U>
Sample code:
public class BiConsumerImpl {
public static void main(String args[]) {
Map<Integer,String> map = new HashMap<>();
map.put(1, "one");
map.put(2,"two");
map.put(3,"three");
map.forEach(new BiConsumer<Integer, String>() {
@Override
public void accept(Integer arg0, String arg1) {
System.out.println(arg0 +"---"+arg1);
}
});
}
}
Labels: Bi-consumer functional interface, Consumer functional interface, Java Functional interface
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home