NotsoCleverAlex NotsoCleverAlex - 2 months ago 21
Java Question

How to return keys of a map according to a condition?

I'm learning Java using BlueJ, I have made a class that has a

(Integer, String)
that contains an ID number of somebody and their name.

I want a method to return a collection of all the keys that satisfy a condition, like if their ID number begins with 3 for example. I can't figure out how to do this.

And then another method that returns a collection of the values if they satisfy a condition, I was thinking it would be very similar to the previous method.

I know I need to loop through the map but I am not sure how to write the condition to populate the new map.


Here's an example that returns all the odd keys, in a Collection. Lists and Sets are Collections, in the same way that ArrayLists are Lists. You could change Collection to List (or even ArrayList) in this example and it would do the same thing.

public Collection<Integer> getOddKeys() {
    // keySet is a method of Map that returns a Set containing all the keys (and no values).
    Collection<Integer> result = new ArrayList<Integer>();
    for(Integer key : map.keySet()) {
        if((key % 2) == 0) // if the key is odd...
            result.add(key); // ... then add it to the result
    return result;

You should be able to modify this example to check the values instead - I won't just give you that code, because it's very similar, and easy to figure out if you understand how this example works.

You need to use the values method, which returns a collection of the values, in the same way that keySet returns a collection (more specifically, a set) of the keys. If you're wondering about why keySet returns a set and values doesn't, it's because you can use the same value twice in a map, but you can't use the same key twice.