Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print multiple parameters using Method reference in java8

I'm trying to print out basic hashmap with twoin java.

Map<Integer, String> mp = new HashMap<Integer, String>();
mp.put(10, "apple");
mp.put(20, "orange");
mp.put(30, "banana");

But I can't figure out how to print multiple parameters, when it comes to method reference in java8.

I tried something like this. But it's giving me compile errors.

mp.forEach(System.out::println(i+" "+s););

Please help me to figure out this. Thank you.

like image 462
Dil. Avatar asked Sep 08 '18 13:09

Dil.


2 Answers

You can also print using entrySet

 mp.entrySet().forEach(e->System.out.println(e.getKey()+"="+e.getValue()));
like image 139
ravthiru Avatar answered Oct 19 '22 23:10

ravthiru


I finally found a solution, but using Apache API Pair class (ImmutablePair) in Java 8.

Stream.of(ImmutablePair.of("A", "1"), ImmutablePair.of("B", "0")) .collect(Collectors.toMap(Pair::getLeft, Pair::getRight));

Hope it helps.

like image 29
Francisco M Avatar answered Oct 19 '22 23:10

Francisco M