有什么办法可以把整个Entry
对象放到一个Map
像这样的对象:
map.put(entry);
Run Code Online (Sandbox Code Playgroud)
而不是传递键值对,如:
map.put(key,value);
Run Code Online (Sandbox Code Playgroud)
?
我已经在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> {}
}
Run Code Online (Sandbox Code Playgroud)
的MyMap
接口仅仅是一个扩展的接口Map
通过添加一种以上的方法,该接口public default V put(Entry<K,V> entry)
。除了仅定义方法外,还对默认实现进行了编码。这样做,我们现在可以Map
通过定义一个新的实现MyMap
接口的类并扩展我们选择的map实现类,将该方法添加到实现该接口的
任何类中。所有这些都在一行中!上面代码的底部演示了这一点,其中创建了两个类,每个类都扩展了HashMap和TreeMap实现。
小智 7
要实例化带有条目的地图(与您在 Google Guava 库中所做的方式相同,我发现了这Arrays.asList(T... a)
一点:Sets.newHashSet(T... a)
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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
25184 次 |
最近记录: |