Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the usage of HashMap iterative deletion in Java?

Shulou Source: shulou.com Published: 2022-06-02 13:08:20 10月03日 Update

This article mainly explains "what is the use method of HashMap iterative deletion in Java". The explanation in this article is simple and clear, easy to learn and understand. Please follow the idea of Xiaobian and go deep into it slowly to study and learn "what is the use method of HashMap iterative deletion in Java"!

I. Map iterative deletion

Iterative deletion, without considering concurrency safety, we can see how to support it

1. Very unelegant version.

We know map is not inherited from Collection interface, HashMap also does not provide iteration support, since there is no direct iteration, then I will be honest low b version

Map map = new HashMap();map.put("a", 1);map.put("b", 2);map.put("c", 3);map.put("d", 4);List removeKey = new ArrayList();for (Map.Entry e: map.entrySet()) { if (e.getValue() % 2== 0) { removeKey.add(e.getKey()); }}removeKey.forEach(map::remove);

What about the implementation above? There's nothing wrong with it.

(Why not remove it directly from the loop?)

2. correct posture version

Although Map has no iteration, its entrySet has ah, so we can use it to implement traversal deletion.

Map map = new HashMap();map.put("a", 1);map.put("b", 2);map.put("c", 3);map.put("d", 4);Iterator iterator = map.entrySet().iterator();Map.Entry entry;while (iterator.hasNext()) { entry = iterator.next(); if (entry.getValue() % 2 == 0) { iterator.remove(); }}System.out.println(map);

The above may be an operation gesture we often use, using iterators to manipulate elements

3. concise version

After jdk8, a lot of simple operation methods are provided for containers, and iterative deletion can be said to be simpler.

Map map = new HashMap();map.put("a", 1);map.put("b", 2);map.put("c", 3);map.put("d", 4);map.entrySet().removeIf(entry -> entry.getValue() % 2 == 0);

4. other

As a result of my limited ability, there are inevitably omissions and mistakes. If you find bugs or have better suggestions, you are welcome to criticize and correct them

Thank you for reading, the above is "Java HashMap iterative deletion method is what" content, after learning this article, I believe we have a deeper understanding of Java HashMap iterative deletion method is what this problem, the specific use of the situation also needs to be verified. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

Tags: Iteration usage method content learning simplicity posture support elegance security honesty family individual element premise can be passed container that is suggestion Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Shulou Technology Shulou Tech Info Linux Huawei