Skip to content

Instantly share code, notes, and snippets.

@akhikhl
Created December 27, 2013 22:39
Show Gist options
  • Save akhikhl/8153642 to your computer and use it in GitHub Desktop.
Save akhikhl/8153642 to your computer and use it in GitHub Desktop.
Sorting hashmap float -> float by values
import java.util.Map;
rand = new Random();
float random(float minX, float maxX) {
rand.nextFloat() * (maxX - minX) + minX
}
// Note the HashMap's "key" is a String and "value" is an Integer
HashMap<Float,Float> hm = new HashMap<Float,Float>();
// Putting key-value pairs in the HashMap
for (int i = 0; i < 10; i++) {
float pos = random(-50, 50);
float time = random(0, 50);
hm.put(time, pos);
}
println 'UNSORTED'
// Using an enhanced loop to interate over each entry
for (Map.Entry me : hm.entrySet()) {
print("key is " + me.getKey());
println(" value is " + me.getValue());
}
List<Map.Entry<Float, Float>> entries = new ArrayList<Map.Entry<Float, Float>>(hm.entrySet())
java.util.Collections.sort(entries, new Comparator<Map.Entry<Float, Float>>() {
int compare(Map.Entry<Float, Float> e1, Map.Entry<Float, Float> e2) {
return e2.getValue() - e1.getValue(); // reverse order sort
}
});
Map<Float, Float> m = new LinkedHashMap<Float, Float>();
for(Map.Entry<Float, Float> e : entries)
m.put(e.getKey(), e.getValue());
println 'SORTED'
for (Map.Entry me : m.entrySet()) {
print("key is " + me.getKey());
println(" value is " + me.getValue());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment