How to print multiple parameters using Method reference in java8

You can write a separate method, for example:

public static <K, V> void printEntry(Map.Entry<K, V> e) {
    System.out.println(e.getKey() + " " + e.getValue());
}

map.entrySet().forEach(Demo::printEntry);

Or, if the Map.Entry<K, V>.toString() meets your requirements:

map.entrySet().forEach(System.out::println);

// 20=orange
// 10=apple
// 30=banana

Edit: Also, following @Holger's advice, you can safely omit the type parameters as long as the code inside the method doesn't depend on them:

public static void printEntry(Object k, Object v) {
    System.out.println(k + " " + v);
}

map.forEach(Demo::printEntry);

Might be contradictory to other answers, yet I really don't see a need of you using a method reference here. IMHO,

mp.forEach((i, s) -> System.out.println(i + " " + s));

is far better than method reference for such a use case.


You cannot specify the whitespace by using the method reference System.out::println.
The argument passed to System.out::println is inferred by the BiConsumer parameter of Map.forEach(BiConsumer).

But you could format the expected String with map(), in this way, the argument inferred in System.out::println would be the formatted string, what you need :

mp.entrySet()
  .stream()
  .map(e-> e.getKey() + " " + e.getValue())
  .forEach(System.out::println);

You can't. The language does not allow that, there is no implicit i and s there that can be passed to a method reference that way. What u can do, no idea why, but you could:

private static <K, V> void consumeBoth(K k, V v) {
     //Log how u want this
}

And use it with:

map.forEach(Yourclass::consumeBoth)

But this can be done in place with a lambda expression, I really see no benefit for this small example