2016-09-11 23 views
13

有沒有我可以把整個Entry對象到Map對象喜歡的任何方式:如何在地圖中輸入條目?

map.put(entry); 

,而不是傳遞一個鍵值對,如:

map.put(key,value); 

+1

是否有一個原因'map.put(entry.getKey(),entry.getValue())'不滿意? – ajb

+4

因爲'map.put(entry.getKey(),entry.getValue())'是多餘的,可以簡化爲'map.put(entry)',它更加簡潔和可讀。在我的 意見中,'java.util'包的'Map'接口應該有'V put(條目條目)'方法。 – pgmank

+1

_什麼時候你需要這樣一種方法 - 用例是什麼?我認爲它不在API中,因爲[YAGNI](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it)。 –

回答

3

我已經在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> {} 
} 

MyMap接口僅僅是通過添加一種以上的方法,所述public default V put(Entry<K,V> entry)延伸Map接口 的接口。 除了定義方法外,默認實現編碼爲 。這樣做,我們現在可以將此方法添加到實現接口的任何類中,只需定義一個實現接口並擴展我們選擇的地圖實現類的新類。所有 在一行!這在上面代碼的底部進行了演示,其中創建了兩個類,每個類都擴展了HashMap和TreeMap 實現。

相關問題