Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr Iteraotr

I. Map Iteratively deleted

Iterative deletion, without considering concurrency safety, let’s see how it can be supported

1. The very inelegant version

We know that Map does not inherit from the Collection interface, and HashMap does not provide iteration support. Since we can’t iterate directly, I’ll just stick with low B

Map<String, Integer> map = new HashMap<>();
map.put("a".1);
map.put("b".2);
map.put("c".3);
map.put("d".4);

List<String> removeKey = new ArrayList<>();
for (Map.Entry<String, Integer> e: map.entrySet()) {
	if (e.getValue() % 2= =0) {
	    removeKey.add(e.getKey());
	}
}
removeKey.forEach(map::remove);
Copy the code

What about the implementation above? Nothing wrong with it

(Why not just delete it in traversal?)

2. Correct posture

Although Map does not iterate, its entrySet does, so we can use it for traversal deletion

Map<String, Integer> map = new HashMap<>();
map.put("a".1);
map.put("b".2);
map.put("c".3);
map.put("d".4);

Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
Map.Entry<String, Integer> entry;
while (iterator.hasNext()) {
    entry = iterator.next();
    if (entry.getValue() % 2= =0) {
        iterator.remove();
    }
}
System.out.println(map);
Copy the code

This is probably the most common manipulation we use, using iterators to manipulate elements

3. The concise version

With jdK8, there are a lot of neat ways to manipulate containers, and iterative deletion is even easier

Map<String, Integer> 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);
Copy the code

4. Other

As far as the letter is not as good as, has been the content, purely one’s own words, because of the limited personal ability, it is hard to avoid omissions and mistakes, such as finding bugs or better suggestions, welcome criticism and correction, not grudging gratitude

  • Micro Blog address: Small Gray Blog
  • QQ: a gray /3302797840
  • Personal site Blog: one is gray liuyueyi. Making. IO/hexblog