简体   繁体   English

Java hashmap迭代器

[英]Java hashmap iterator

I want to make the method removeValue( "a", "x") . 我想使方法removeValue( "a", "x")
It must delete all keys and values between the letters. 它必须删除字母之间的所有键和值。 For example: 例如:

{1=a,2=b,3=c,5=x}  ->> {1=a,5=x}

I tried with equals and iterator but I don't know how to write it. 我尝试过用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);
        }
    }
}

Try the following code.I'm using treemap to maintain the order and then iterating to remove the elements. 尝试下面的代码。我正在使用treemap维护顺序,然后迭代以删除元素。

 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

First of all, a HashMap never keeps the orders of the Object which are put in it. 首先, HashMap永远不会保留Object的顺序。 So you need to use LinkedHashMap which maintains its insertion order. 因此,您需要使用LinkedHashMap来维持其插入顺序。 For removal of Object you need to make use of Iterator 要删除Object您需要使用Iterator

Map testMap = new LinkedHashMap<Integer, String>(); If your key is of any other type except Integer change it accordingly. 如果您的keyInteger以外的其他任何类型,请相应地进行更改。

So for your requirement, you can use the below code :- 因此,根据您的要求,您可以使用以下代码:-

 public static void testKey(Map<Integer, String> testMap, String startValue,
            String endValue) {
 if(!testMap.containsValue(startValue) || !testMap.containsValue(endValue))
            return; // if start/end value is not present in Map then no change at all
        Iterator<Map.Entry<Integer, String>> iter = testMap.entrySet()
                .iterator();
        boolean deleteFlag = false;
        while (iter.hasNext()) {
            Map.Entry<Integer, String> entry = iter.next();
            if (endValue.equalsIgnoreCase(entry.getValue())) {
                deleteFlag = false;
            }
            if (deleteFlag)
                iter.remove();
            if (startValue.equalsIgnoreCase(entry.getValue())) {
                deleteFlag = true;
            }

        }
    }

public static void main(String[] args) {
        Map m = new LinkedHashMap<Integer, String>();
        m.put(1, "a");
        m.put(2, "b");
        m.put(3, "c");
        m.put(5, "x");
        System.out.println("before : "+m);
        removeValue(m, "a", "x");
        System.out.println("after : "+m);
    }

Output 产量

before : {1=a, 2=b, 3=c, 5=x}
after : {1=a, 5=x}

Using an Iterator allows you to remove entries on the fly. 使用Iterator可让您即时删除条目。

public void removeRange(Map<Integer, String> map, String from, String to) {
    // Walk each entry.
    for (Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator(); it.hasNext();) {
        // What is the value?
        String v = it.next().getValue();
        if (v.compareTo(from) > 0 && v.compareTo(to) < 0) {
            // In the specified range! Remove it.
            it.remove();
        }
    }

}

public void test() {
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "a");
    map.put(2, "b");
    map.put(3, "c");
    map.put(4, "w");
    map.put(5, "x");
    System.out.println("Before:" + map);
    removeRange(map, "a", "x");
    System.out.println("After:" + map);
}

prints 版画

Before:{1=a, 2=b, 3=c, 4=w, 5=x} 之前:{1 = a,2 = b,3 = c,4 = w,5 = x}

After:{1=a, 5=x} 之后:{1 = a,5 = x}

If you are using Java 8 you can also stream and filter a Map. 如果您使用的是Java 8,则还可以流式传输和过滤Map。

public <K, V> Map<K, V> filter(Map<K, V> map, Predicate<Map.Entry<K, V>> filter) {
    return map.entrySet()
            .stream()
            // Filter out the unwanted ones.
            .filter(filter)
            // Fold back into a new Map.
            .collect(Collectors.toMap(
                            (Map.Entry<K, V> e) -> e.getKey(),
                            (Map.Entry<K, V> e) -> e.getValue()));
}

public Map<Integer, String> removeRangeWithStream(Map<Integer, String> map, String from, String to) {
    return filter(map,
            (Map.Entry<Integer, String> e) -> e.getValue().compareTo(from) <= 0 || e.getValue().compareTo(to) >= 0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM