我正在尝试用twoin java打印出基本的hashmap
。
Map<Integer, String> mp = new HashMap<Integer, String>();
mp.put(10, "apple");
mp.put(20, "orange");
mp.put(30, "banana");
但是当涉及到java8中的method reference
时,我不知道如何打印多个参数。
我尝试过这样的事情。但它给了我编译错误。
mp.forEach(System.out::println(i+" "+s););
请帮我弄清楚这一点。 谢谢。
可能与其他答案相矛盾,但我真的认为您不需要在这里使用方法参考。恕我直言,
mp.forEach((i, s) -> System.out.println(i + " " + s));
对于这样的用例,比方法参考要好得多。
你不能。该语言不允许这样做,那里没有隐式的 i 和 s 可以以这种方式传递给方法引用。你能做什么,不知道为什么,但你可以:
private static <K, V> void consumeBoth(K k, V v) {
//Log how u want this
}
并将其用于:
map.forEach(Yourclass::consumeBoth)
但这可以通过 lambda 表达式就地完成,我真的认为这个小例子没有任何好处
您可以编写单独的方法,例如:
public static <K, V> void printEntry(Map.Entry<K, V> e) {
System.out.println(e.getKey() + " " + e.getValue());
}
map.entrySet().forEach(Demo::printEntry);
或者,如果Map.Entry<K, V>.toString()
符合您的要求:
map.entrySet().forEach(System.out::println);
// 20=orange
// 10=apple
// 30=banana
编辑:此外,按照@Holger的建议,只要方法中的代码不依赖于它们,您就可以安全地省略类型参数:
public static void printEntry(Object k, Object v) {
System.out.println(k + " " + v);
}
map.forEach(Demo::printEntry);
不能使用方法引用System.out::println
指定空格。
传递给System.out::println
的参数由Map.forEach(BiConsumer)
的BiConsumer
参数推断。
但是你可以用map()
格式化预期的String
,这样,System.out::println
中推断的参数将是格式化的字符串,你需要什么:
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()));
我终于找到了一个解决方案,但在Java 8中使用了Apache API Pair类(ImmutablePair(。
Stream.of(ImmutablePair.of("A", "1"), ImmutablePair.of("B", "0")) .collect(Collectors.toMap(Pair::getLeft, Pair::getRight));
希望对您有所帮助。