0

I have a HashMap which is populated with String and Integer:

Map<String, Integer> from_table;
from_table = new HashMap<String, Integer>();

Next i want to get all the keys of items which there value (the Integer) is above x.

For example all the keys which their value is over 4.

Is there a fast method for doing that?

Thnaks!

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
Michael A
  • 5,770
  • 16
  • 75
  • 127
  • 2
    Nothing faster than a loop unless you use a sorted version of hashmap. – selig Jun 24 '13 at 19:35
  • What is the sorted version? can i define sorted version with String and an Integer? – Michael A Jun 24 '13 at 19:37
  • It's either sorting, looping or, if you're in to spare some extra memory, having an extra map where for "the other way around" (`Map`) – Fritz Jun 24 '13 at 19:38
  • [This question](http://stackoverflow.com/questions/780541/how-to-sort-hash-map) is relevant. – selig Jun 25 '13 at 12:50

4 Answers4

1
public static void printMap(Map mp) {
    for(Map.Entry pairs : mp.entrySet()) {
        if(pairs.getValue() >= 4)
        {
          System.out.println(pairs.getKey());
        }
    }
}
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
orangegoat
  • 2,523
  • 1
  • 15
  • 17
0

Well, iterate over the key-value pairs and collect keys where values meet the criteria

//collect results here
List<String> resultKeys= new ArrayLIst<String>();

//hash map iterator
Iterator<String> it = from_table.keySet();
while(it.hasNext()) {
    //get the key
    String key= it.next();
    /get the value for the key
    Integer value= from_map.get(key);
    //check the criteria
    if (value.intValue() > x) {
        resultKeys.add(key);
    }
}
darijan
  • 9,725
  • 25
  • 38
0

Not in standard Java. Guava has method called filter doing exactly this as a one-liner (+ the predicate).

Jiri Kremser
  • 12,471
  • 7
  • 45
  • 72
0

As the above solution states there is nothing faster than just looping through, but an alternative solution would be to edit the function to put something in the map and have it check if there are 4 or more items, if there are it adds it to a new list with only objects with a count of more than 4

aaronman
  • 18,343
  • 7
  • 63
  • 78