Pergunta

Say I have a HashMap with string as the key and integer as a value

("a",10)
("b",2)
("c",9)
("d",34)
("e",12)

I want to put the keys which have a value greater than 10 into a ArrayList. So the result would be

("d","e")

as their values are greater than 10

I have researched this and all the methods I found change the HashMap into TreeMap or something else, but this is for homework so I cannot change the HashMap

Foi útil?

Solução

You cannot do better than iterating through all elements. So the solution is pretty simple:

List<String> res = new ArrayList<String>();

for (String crtKey : map.keySet()) {
    Integer value = map.get(crtKey);

    if ( value != null && value > 10) 
        res.add(crtKey);
    }
}

Outras dicas

With Java 8 you can use the following construct:

List<String> filteredKeys = map.entrySet().stream()
                               .filter(e -> e.getValue() > 10) //keep values > 10
                               .map(Entry::getKey) //we only want the keys
                               .collect(toList()); //put them in a list

try this:

ArrayList<String> mylist = new ArrayList<String>();

for (String key : map.keySet()) {
    int value = map.get(key);
    if (key > 10) {
        mylist.add(key);
    }
}

Well, since you said it is a homework, I won't give the code, but, I'll give you the basic idea.

Just loop through the hashmap and get the values and store them in a list if it is greater than 10. This is the best that could be done, and is the simplest solution.

So the pseudocode will be something like:

list = []
for each key in hashmap
  if hashmap(key) > 10
    list.append(key)
 Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("a", 10);
        map.put("b",2);
        map.put("c",9);
        map.put("d",34);
        map.put("e",12);
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (entry.getValue() > 10) {
                System.out.println(entry.getKey());
            }
        }
List<String> res = new ArrayList<String>();

for (String crtKey : map.keySet()) {

    Integer value = map.get(crtKey);

    if ( value != null && value > 10) 
        res.add(crtKey);
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top