Java 8 : BiConsumer Functional Interface

java.util.function.BiConsumer

BiConsumer is similar to a Consumer. It accepts two input parameters, but doesn’t return anything.


@FunctionalInterface public class BiConsumer<T, U> {

    void accept(T t, U u); // Performs this operation on the given argument.
    default BiConsumer<T,U> andThen(BiConsumer<? super T,? super U> after)
}

 

Example 1 : BiConsumer

package com.topjavatutorial;

import java.util.function.BiConsumer;

public class TestBiConsumer {

  public static void main(String[] args) {
    BiConsumer<String, String> concatBiConsumer = (x, y) -> {
      System.out.println(x + y);
    };

    concatBiConsumer.accept("Hello", "World");
  }
}

Output:

HelloWorld
 

Example 2 : BiConsumer with Map

For Maps, a BiConsumer’s first parameter represents the key and its second parameter represents the corresponding value.

package com.topjavatutorial;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

public class TestBiConsumer {

  public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    BiConsumer<String, String> biConsumer = (k, v) -> map.put(k, v);
    biConsumer.accept("a", "apple");

    System.out.println(map);
  }
}

Output:

{a=apple}
 

Example 3 : BiConsumer with Method Reference

package com.topjavatutorial;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

public class TestBiConsumer {

  public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    BiConsumer<String, String> biConsumer = map::put;
    biConsumer.accept("a", "apple");

    System.out.println(map);
  }
}

Output:

{a=apple}
 

Consumer vs BiConsumer

A Consumer accepts a single parameter whereas BiConsumer accepts 2 parameters. Both do not return anything.
 

© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags