문제

I'm learning Java using BlueJ, I have made a class that has a HashMap of (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.

다른 팁

You could do the following:

  • Create a holder list
  • Iterator over your map keys using map.keySet().iterator();
  • Check if the key start with 3, if yes add it to the key list.
  • return the keys list.

In your case (if the map is not too big), I'll get all keys of the map, then process them one by one to math my criteria:

Map<Integer, String> myMap=getFromSomeWhere();
for(Integer i : myMap.keySet() {
    String k=String.valueOf(i);
    if(k.startsWith("3")) {
        //do what you want
    }
}
public void CountryAbbriviationMap(String input)
{
        map<string ,string> countrymap =new map<string ,string>{'Australia'=>'AUS','Argentina'=>'ARG', 'India'=>'IND'};

        for(string key : countrymap.keySet())
        {
            if(key.startsWithIgnoreCase('A') && input.startsWithIgnoreCase('A'))
            {
                system.debug(key); //TO GET KEYS
                system.debug(countrymap.get(key)); //TO GET VALUES 
            }
        }  
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top