Java 如何将条目放入地图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39441096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:09:07  来源:igfitidea点击:

How to put an Entry into a Map?

javadictionary

提问by pgmank

Is there any way that I can put a whole Entryobject to a Mapobject like:

有什么方法可以将整个Entry对象放到一个Map对象上,例如:

map.put(entry);

instead of passing a key-value pair like:

而不是传递键值对,例如:

map.put(key,value);

采纳答案by pgmank

I have searched on the Map interface methods but there is no method that takes an entry and puts it in the map. Therefore I have implemented it by myself using a little bit of inheritance and Java 8 interfaces.

我已经搜索了 Map 接口方法,但没有方法可以获取条目并将其放入地图中。因此,我使用一点继承和 Java 8 接口自己实现了它。

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Maps {

    // Test method
    public static void main(String[] args) {
        Map.Entry<String, String> entry1 = newEntry("Key1", "Value1");
        Map.Entry<String, String> entry2 = newEntry("Key2", "Value2");

        System.out.println("HashMap");
        MyMap<String, String> hashMap = new MyHashMap<>();
        hashMap.put(entry1);
        hashMap.put(entry2);

        for (String key : hashMap.keySet()) {
            System.out.println(key + " = " + hashMap.get(key));
        }

        System.out.println("\nTreeMap");
        MyMap<String, String> treeMap = new MyTreeMap<>();
        treeMap.put(entry1);
        treeMap.put(entry2);


        for (String key : treeMap.keySet()) {
            System.out.println(key + " = " + treeMap.get(key));
        }
    }


    /**
     * Creates a new Entry object given a key-value pair.
     * This is just a helper method for concisely creating a new Entry.
     * @param key   key of the entry
     * @param value value of the entry
     * 
     * @return  the Entry object containing the given key-value pair
     */
    private static <K,V> Map.Entry<K,V> newEntry(K key, V value) {
        return new AbstractMap.SimpleEntry<>(key, value);
    }

    /**
     * An enhanced Map interface.
     */
    public static interface MyMap<K,V> extends Map<K,V> {

        /**
         * Puts a whole entry containing a key-value pair to the map.
         * @param entry 
         */
        public default V put(Entry<K,V> entry) {
            return put(entry.getKey(), entry.getValue());
        }
    }

    /**
     * An enhanced HashMap class.
     */
    public static class MyHashMap<K,V> extends HashMap<K,V> implements MyMap<K,V> {}

    /**
     * An enhanced TreeMap class.
     */
    public static class MyTreeMap<K,V> extends TreeMap<K,V> implements MyMap<K,V> {}
}

The MyMapinterface is just an interface that extends the Mapinterface by adding one more method, the public default V put(Entry<K,V> entry). Apart from just defining the method, a default implementation is coded too. Doing that, we can now add this method to any class that implements the Mapinterface just by defining a new class that implements the MyMapinterface and extending the map implementation class of our choice. All of that in one line! This is demonstrated in the bottom of the code above where two classes are created each extending the HashMap and the TreeMap implementations.

MyMap接口仅仅是一个扩展的接口Map通过添加一种以上的方法,该接口public default V put(Entry<K,V> entry)。除了只定义方法之外,还对默认实现进行了编码。这样做后,我们现在Map只需定义一个实现MyMap接口的新类并扩展我们选择的地图实现类,就可以将此方法添加到任何实现该接口的 类中。所有这些都在一行中!这在上面代码的底部进行了演示,其中创建了两个类,每个类都扩展了 HashMap 和 TreeMap 实现。

回答by Matt De Poorter

To instantiate a Map with Entries (in the same way as you can do Arrays.asList(T... a)or Sets.newHashSet(T... a)in Google Guava library, I found this:

要使用条目实例化地图(以与您相同的方式Arrays.asList(T... a)Sets.newHashSet(T... a)在 Google Guava 库中的方式),我发现了以下内容:

import java.util.AbstractMap;
import java.util.Map;

public class MapWithEntries {

    private static final Map.Entry<String, String> ENTRY_1 = new AbstractMap.SimpleEntry<>("A", "Hello");
    private static final Map.Entry<String, String> ENTRY_2 = new AbstractMap.SimpleEntry<>("B", "World");

    private static final Map<String, String> MAP_WITH_ENTRIES = Map.ofEntries(ENTRY_1, ENTRY_2);
}

回答by kcyc

Solution if you're using Java Platform SE 8:

如果您使用的是 Java Platform SE 8,则解决方案:

SimpleEntry and SimpleImmutableEntry classes implement interface Map.Entry

SimpleEntry 和 SimpleImmutableEntry 类实现接口 Map.Entry

import java.util.AbstractMap.SimpleEntry;
import java.util.AbstractMap.SimpleImmutableEntry;

List<Map.Entry<K, V>> map = new ArrayList<>(); 
map.add(new SimpleEntry<K,V>(key,value));
map.add(new SimpleImmutableEntry<K,V>(key,value)); // constructs immutable entries for thread-safe operation

回答by mattlaw

Guava's ImmutableMap.Buildertakes entries directly.

Guava'sImmutableMap.Builder直接接受条目

Obviously that doesn't directly modify an existing Map, but it might well scratch the same itch.

显然,这不会直接修改现有的Map,但它很可能会刮伤同样的痒。