没有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;
}
'Map'没有被values_分类。 – 2014-09-25 16:13:21
所以最新的实际问题在这里?你只是问如何做map.put(“s”,1)? – Dave 2014-09-25 16:18:41
我在问如何比较这些值和递增计数器,具体取决于它们的值。如果它们具有相同的值,则计数器保持不变并且被存储而不是该值。 – 2014-09-25 16:22:28