Java HashMap 迭代器

标签 java hashmap iterator key key-value

我想要使用方法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/

相关文章:

java - Hibernate - MYSQLDialect 中的函数 rand()

用于访问对象元素的 Javascript Hashmap

java - IdentityHashMap 返回的值不正确 - 为什么?

xpath - Xquery 嵌套映射 :merge from xml produces error "expected single value for key, got 0"

java - 是否需要安装 EE 服务器才能使用 JMS?

java - GAE : Unable to set session values inside interceptor 上的 Struts 2

java - Python 生成的 XML 中的错误

php - 如何使用 RecursiveIteratorIterator 忽略目录?

java - 如何删除迭代器循环并允许 cellDateType 在 xlsx java 中工作?

java - 如何使用迭代器复制列表