我想要使用方法removeValue( "a", "x")
。
它必须删除字母之间的所有键和值。例如:
{1=a,2=b,3=c,5=x} ->> {1=a,5=x}
我尝试过使用 equals 和 iterator,但我不知道如何编写它。
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<Integer, String> map = new TreeMap<Integer, String>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.put(4, "w");
map.put(5, "x");
ArrayList<Integer> intList = new ArrayList<Integer>();
for (Iterator<Integer> it = map.keySet().iterator(); it.hasNext();) {
int key = 0;
if (it.next() == 1) {
while(true) {
key = it.next();
if(key==5)break;
intList.add(key);
}
}
}
//removing from the map in separate loop to avoid concurrent modification exception
for (int i : intList) {
map.remove(i);
}
System.out.println(map.size()); //2
关于Java HashMap 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31183903/