How to iterate over MultivaluedMap using forEach and a lambda expression

ksl*_*ksl 3 java foreach lambda java-8

Java 8 allows iteration over a Map using forEach and a lambda expression as follows:

myMap.forEach((k, v)->{ System.out.println("Key: " + k + " Value: " + v); });
Run Code Online (Sandbox Code Playgroud)

Is it possible to iterate over a MultivaluedMap using forEach and a lambda expression?

UDPATE

How do I call foo with 2 String parameters for a MultivaluedMap<String, String>?

myMultiMap.forEach((k, v)->{ foo(k, v); });
Run Code Online (Sandbox Code Playgroud)

And*_*lko 5

The interface MultivaluedMap<K, V> extends the Map<K,List<V>> interface, therefore, there is forEach method and that is possible to use it.

new MultivaluedHashMap<String, String>()
        .forEach((String key, List<String> list)-> { ... });
Run Code Online (Sandbox Code Playgroud)

I don't know what your foo method does, but I suggest* considering my point about that:

public <K, V> void foo(K key, V... values) { ... }
Run Code Online (Sandbox Code Playgroud)

In such case, you needn't write inner forEach inside the lambda.
*(it is wrong as explained @Holder in the comments)

So, there is the only one proper way:

map.forEach((k, l) -> l.forEach( v -> foo(k, v)));
Run Code Online (Sandbox Code Playgroud)

  • 如果您想知道输出中的双引号 `[[ … ]]`:由于 `foo` 上的无意义类型参数 `&lt;K, V&gt;`,这看起来只是在做正确的事情。所以`V` 被推断为`List&lt;String&gt;` 并且每个列表都作为varargs 参数的第一个参数传递,你打印它就像被包装到另一个列表中。当 `foo` 不是可变参数方法时,你甚至可以调用它,只要 `V` 可以是调用者提供的任何东西。但是 OP 想要调用一个处理 `String`s 的方法...... (2认同)