DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Linked List Popular Problems Vol. 1
  • Java: Why a Set Can Contain Duplicate Elements
  • What Is Ant, Really?
  • DataWeave Interview Question: Concatenate Elements of an Array

Trending

  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • The Modern Data Stack Is Overrated — Here’s What Works
  • Unlocking AI Coding Assistants Part 4: Generate Spring Boot Application
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  1. DZone
  2. Coding
  3. Java
  4. Removing Elements From a Map in Java

Removing Elements From a Map in Java

Want to learn more about removing elements from a Map?

By 
Dan Newton user avatar
Dan Newton
·
Updated Mar. 06, 19 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
103.9K Views

Join the DZone community and get the full member experience.

Join For Free

This is a very short and simple post on removing elements from a Map in Java. We will be focusing on removing multiple elements and ignoring the fact that you can remove a single element using Map.remove.

The Map below will be used for this post:

Map<Integer, String> map = new HashMap<>();
map.put(1, "value 1");
map.put(2, "value 2");
map.put(3, "value 3");
map.put(4, "value 4");
map.put(5, "value 5");


There are a few ways to remove elements. You could loop through the code manually and remove them:

for(Iterator<Integer> iterator = map.keySet().iterator(); iterator.hasNext(); ) {
  Integer key = iterator.next();
  if(key != 1) {
    iterator.remove();
  }
}


This is how you would do it without access to Java 8+. The Iterator is needed to prevent ConcurrentModificationExceptions when removing elements from the Map.

If you do have access to newer versions of Java (8+), then you can choose from the below instead:

// remove by value
map.values().removeIf(value -> !value.contains("1"));
// remove by key
map.keySet().removeIf(key -> key != 1);
// remove by entry / combination of key + value
map.entrySet().removeIf(entry -> entry.getKey() != 1);


removeIf is a method available to Collections. Yes, a Map itself is not a Collection and does not have access to removeIf itself. But, by using: values, keySet, or entrySet, a view of the Map's contents is returned. This view implements Collection allowing removeIf to be called on it.

The contents returned by values, keySet, and entrySet are very important. Below is an extract of the JavaDoc for values:

* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are
* reflected in the collection, and vice-versa.
*
* The collection supports element removal, which removes the corresponding
* mapping from the map, via the {@code Iterator.remove},
* {@code Collection.remove}, {@code removeAll},
* {@code retainAll} and {@code clear} operations.


This JavaDoc explains that the Collection returned by values is backed by the Map and that changing either the Collection or the Map will alter the other. I don't think I can explain what the JavaDoc is saying any better than what is already written there... So, I'll stop trying on that part now. I have only shown the documentation for values, but you can trust me when I say that keySet and entrySet are also both backed by the Map 's contents. You can read the docs yourself if you don't believe me.

This also links back to the first example using an older Java version. The documentation specifies that Iterator.remove can be used. This is what is used earlier. Furthermore, the implementation of removeIf is very similar to the Iterator example. After talking about it, I might as well show it:

default boolean removeIf(Predicate<? super E> filter) {
  Objects.requireNonNull(filter);
  boolean removed = false;
  final Iterator<E> each = iterator();
  while (each.hasNext()) {
    if (filter.test(each.next())) {
      each.remove();
      removed = true;
    }
  }
  return removed;
}


There is a bit extra to it. But, otherwise, it is pretty much the same.

So, that's that. Not much to conclude other than me telling you to remember that using: values, keySet, or entrySet will provide access to removeIf, allowing easy removal of Map entries.



If you enjoyed this article and want to learn more about Java Collections, check out this collection of tutorials and articles on all things Java Collections.

Java (programming language) Element

Published at DZone with permission of Dan Newton, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Linked List Popular Problems Vol. 1
  • Java: Why a Set Can Contain Duplicate Elements
  • What Is Ant, Really?
  • DataWeave Interview Question: Concatenate Elements of an Array

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!