2014-09-25 47 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