2014-09-25 19 views
0

我有地圖,它有一些鍵和值,我想更新下面列出的值。 該數據僅用於此測試示例。如何更新java中的地圖中的值

Map<String, Double> map = new LinkedHashMap<String, Double>(); 
map.put("s",100.00); 
map.put("d",80.00); 
map.put("a",80.00); 
map.put("e",80.00); 
map.put("c", 50.00); 
map.put("w", 50.00); 
map.put("q", 20.00); 

更新後和我打印地圖它應該給我: [S = 1,d = 2,α= 2,E = 2,C = 3,W = 3,Q = 4] 幾乎我會比較價值並增加它們。我認爲他們是平等的,它保持不變。地圖按值排序。 我已經在列表中存儲了值,並在列表中完成了這一操作,但無法考慮如何使用地圖來完成此操作。謝謝!

+1

'Map'沒有被values_分類。 – 2014-09-25 16:13:21

+1

所以最新的實際問題在這裏?你只是問如何做map.put(「s」,1)? – Dave 2014-09-25 16:18:41

+0

我在問如何比較這些值和遞增計數器,具體取決於它們的值。如果它們具有相同的值,則計數器保持不變並且被存儲而不是該值。 – 2014-09-25 16:22:28

回答

0

沒有100%地肯定你問什麼,但也許是這樣的:

Map<String, Double> map = new LinkedHashMap<String, Double>(); 
map.put("s",100.00); 
map.put("d",80.00); 
map.put("a",80.00); 
map.put("e",80.00); 
map.put("c", 50.00); 
map.put("w", 50.00); 
map.put("q", 20.00); 

Map<String, Integer> newMap = new LinkedHashMap<>(); 

double lastVal = -1; 
int i = 0; 
for (Map.Entry<String, Double> entry : map.entrySet()) { 
    if (entry.getValue() != lastVal) 
     i++; 
    newMap.put(entry.getKey(), i); 
    lastVal = entry.getValue(); 
} 
System.out.println(newMap); 

輸出:

{s=1, d=2, a=2, e=2, c=3, w=3, q=4} 

這裏有一個稍微長一點,但更好更穩定的解決方案:

public static void main(String[] args) { 
    Map<String, Double> map = new LinkedHashMap<String, Double>(); 
    map.put("s",100.00); 
    map.put("d",80.00); 
    map.put("a",80.00); 
    map.put("e",80.00); 
    map.put("c", 50.00); 
    map.put("w", 50.00); 
    map.put("q", 20.00); 

    Map<Double, List<String>> inverted = invertMap(map); 
    List<Double> keys = new ArrayList<>(inverted.keySet()); 
    Collections.sort(keys, Comparator.reverseOrder()); 

    Map<String, Integer> result = new LinkedHashMap<>(); 

    int i = 1; 
    for (Double key : keys) { 
     for (String s : inverted.get(key)) 
      result.put(s, i); 
     i++; 
    } 
    System.out.println(result); 
} 

static <K, V> Map<V, List<K>> invertMap(Map<K, V> map) { 
    Map<V, List<K>> result = new HashMap<>(); 
    for (K key : map.keySet()) { 
     V val = map.get(key); 
     if (!result.containsKey(val)) 
      result.put(val, new ArrayList<>()); 
     result.get(val).add(key); 
    } 
    return result; 
} 
+0

這就是我正在尋找的。謝謝! – 2014-09-25 16:35:21

+0

使用第二種解決方案。它不依賴輸入映射的插入順序。 – aioobe 2014-09-25 16:36:18