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.
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 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
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);
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);
您还可以使用 entrySet 打印
mp.entrySet().forEach(e->System.out.println(e.getKey()+"="+e.getValue()));
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.