-1

I have a small HashMap (less than 100 entries) that contains a unique object (of my design) as the key and a Double as the value.

I need to retrieve n number of objects that have the lowest values.

So say my HashMap looked like this and I wanted the lowest 3.

Object, 4.0

Object, 5.0

Object, 2.0

Object, 12.0

Object, 10.0

Object, 3.0

I would want to fetch the first, third, and last entries as those have the lowest values.

I know there are methods such as Collections.min which I could run on the HashMap but I need more than just the lowest value and I need to know the key it corresponds to as well. Research has also led me to come across Selection Algorithms but I am confused and not quite sure how to use these. I apologise if a question of this sort has been asked before, I searched for a long time and could not find anything. Thanks pre-emptively for your help.

3 Answers3

3
List<Entry<Key, Double>> lowestThreeEntries = map.entrySet()
        .stream()
        .sorted(Comparator.comparing(Entry::getValue))
        .limit(3)
        .collect(Collectors.toList());
shmosel
  • 49,289
  • 6
  • 73
  • 138
  • Hi, I tried your solution and it probably would have worked but it required Java SE 8 and I'm currently using 7. Thanks for your help though! – user3084433 May 18 '16 at 15:42
0

Put all then entries of your map inside an array. Then, implement a Comparator<Map.Entry<Key,Value>> which compares the map entries according to the value they hold.

And finally, sort the entries of the map according to your shiny comparator. (You can use Arrays.sort)

T. Claverie
  • 11,380
  • 1
  • 17
  • 28
0

Consider inverting your map and using a 'MultiMap' (effectively a more user friendly implementation of Map<Key, List<Value>>), the Guava TreeMultiMap should do exactly what you're after.

http://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/TreeMultimap.html

Edit - Added example (using String in place of the custom object for brevity)

    TreeMultimap<Double, String> map = TreeMultimap.<Double, String>create();
    map.put(4.0, "a");
    map.put(5.0, "b");
    map.put(2.0, "c");
    map.put(12.0, "d");
    map.put(10.0, "e");
    map.put(3.0, "f");

    Iterator<String> iterator = map.values().iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }

This will print out the strings in ascending order according to the double value (c, f, a, b, e, d)

Graham S
  • 176
  • 1
  • 12