簡體   English   中英

Java hashmap迭代器

[英]Java hashmap iterator

我想使方法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);
        }
    }
}

嘗試下面的代碼。我正在使用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

首先, HashMap永遠不會保留Object的順序。 因此,您需要使用LinkedHashMap來維持其插入順序。 要刪除Object您需要使用Iterator

Map testMap = new LinkedHashMap<Integer, String>(); 如果您的keyInteger以外的其他任何類型,請相應地進行更改。

因此,根據您的要求,您可以使用以下代碼:-

 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);
    }

產量

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

使用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);
}

版畫

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

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

如果您使用的是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