Wige
Wige

Reputation: 3918

Java HashMap How to get the set of keys that is not linked to the HashMap?

I have a HashMap that stores data that need to be changed. I need to figure out how many fields are in the HashMap, not counting "comments" and "debug". My solution was to simply get the keySet, and remove the columns I don't want to count, like this:

// Create and populate the HashMap
HashMap<String, String> updates = new HashMap<>();
makeUpdates(updates);
if (somecondition) {
    updates.put("comments", commentUpdater("Some Comment"));
}
updates.put("debug", getDebugInfo());

// Get the updated keys
Set<String> updatedFields = updates
updatedFields.remove("comments");
updatedFields.remove("debug");
System.out.println("The following " + updatedFields.size() + 
    " fields were updated: " + updatedFields.toString());

The problem, of course, is that removing "comments" and "debug" from the set also removes them from the HashMap. How can I break this link, or get a copy of the set that is not linked to the HashMap?

Upvotes: 2

Views: 399

Answers (2)

Thiyagu
Thiyagu

Reputation: 17910

Create a copy

Set<String> updatedFields = new HashSet<>(updates.keySet());

Now, you can remove strings from updatedFields which won't affect the updates map.

Or as @Elliott Frisch mentioned, you can filter it

Set<String> updatedFields = updates.keySet()
                                   .stream()
                                   .filter(key -> !"comments".equals(key) && !"debug".equals(key))
                                   .collect(Collectors.toSet());

Upvotes: 3

Eran
Eran

Reputation: 393966

Create a new HashSet and initialize it with the elements of the HashMap's keySet():

Set<String> updatedFields = new HashSet<>(updates.keySet());

Upvotes: 1

Related Questions