简体   繁体   中英

Constructing Map from Set<Map.Entry> in Java 7?

java.util.Map comes with entrySet() method that...

Returns a Set view of the mappings contained in this map.

Is there a single method call or a series of API calls to reconstruct a set out of the set using the Java 7 API as marked what do I need to put here? in the following code sample?

package so;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class SetMapExample {
    public static void main(String[] args) {
        Map<String, String> m = new HashMap<String, String>();
        m.put("k1", "v1");
        m.put("k2", "v2");
        Set<Map.Entry<String, String>> s = m.entrySet();
        Map<String, String> ms = s...   // what do I need to put here?
    }
}

I don't want to use for loop if possible and expect a similar method to entrySet on Map , but I can't seem to find one.

Apache Commons Collections provides MapUtils.putAll which can do what you want, but under the covers that just does the for loop logic that you want to avoid, so you might as well just do the looping yourself...

In general there's no way to construct a Map out of a Set of entries that won't require you (or the library function you are calling) to iterate over the entries at least once - there might be special cases, eg if you have a list of entries that you know are sorted by key then you could write a read-only map implementation on top of that that uses binary search to find the key.

A Set uses a Map behind the scenes and the values in the Set are in fact keys in the Map . So, it is not possible to accomplish what you want/need without a for loop. Using plain Java (no other fancy frameworks), you only can do this:

for(Map.Entry<String,String> entry : s) {
    ms.put(entry.getKey(), entry.getValue());
}

JDK does not provide such method, however you can use Guava if you want. Tip: use Transofrmers or Maps . You have to write your own "transformer" - one-line implementation of Guava's Function . If you implement it as generic top level class you can re-use it later.

java.util.Map#entrySet()是涉及元素添加的单视图操作,并且接受Set<Map.Entry<K, V>>的构造函数似乎是一个非常具体且很少发生的情况。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM