【发布时间】:2015-09-19 22:38:33
【问题描述】:
我想做removeValue( "a", "x")的方法。
它必须删除字母之间的所有键和值。例如:
{1=a,2=b,3=c,5=x} ->> {1=a,5=x}
我尝试过使用 equals 和迭代器,但我不知道如何编写它。
public class CleanMapVal {
public static void main(String[] args) throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
map.put("4", "w");
map.put("5", "x");
System.out.println( map );
for (Iterator<String> it = map.keySet().iterator(); it.hasNext();)
if ("2".equals(it.next()))
it.remove();
System.out.println(map);
}
public static <K, V> void removeValue(Map<K, V> map) throws Exception {
Map<K, V> tmp = new HashMap<K, V>();
for (Iterator<K> it = map.keySet().iterator(); it.hasNext();) {
K key = it.next();
V val = map.get(key);
if (!tmp.containsValue(val)) {
tmp.put(key, val);
}
}
map.clear();
for (Iterator<K> it = tmp.keySet().iterator(); it.hasNext();) {
K key = it.next();
map.put((K) tmp.get(key), (V) key);
}
}
}
【问题讨论】:
-
你已经有问题了,
Map不能保证其条目的顺序;所以一开始就没有“a和x之间的键”这样的东西。当然,您也可以使用LinkedHashMap,但我怀疑这是一个 XY 问题。 -
我不确定您要做什么。正如@fge 提到的 HashMap 没有保证顺序。 LinkedHashMap 也像 List 一样对其元素进行排序,新元素放在最后,所以你仍然不能通过它们的值(或键)得到保证的元素顺序。因此,假设您有映射
{a=1, b=2, c=3, d=2, e=1}并且您调用removeValue( "1", "3")。结果应该是{a=1, c=3, d=2, e=1}或{a=1, c=3, e=1}还是其他?
标签: java hashmap iterator key key-value