Skip to content

Instantly share code, notes, and snippets.

@martiell
Created November 15, 2012 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save martiell/4079452 to your computer and use it in GitHub Desktop.
Save martiell/4079452 to your computer and use it in GitHub Desktop.
Ranges
import java.util.Map.Entry;
import java.util.TreeMap;
// See http://stackoverflow.com/a/13400317/611182
public class Main {
private static TreeMap<Double, String> m = new TreeMap<Double, String>();
static {
m.put(1.0, "A");
m.put(2.9, null);
m.put(4.0, "B");
m.put(6.0, null);
m.put(6.5, "C");
m.put(10.0, null);
}
private static <K, V> V mappedValue(TreeMap<K, V> map, K key) {
Entry<K, V> e = map.floorEntry(key);
if (e != null && e.getValue() == null) {
e = map.lowerEntry(key);
}
return e == null ? null : e.getValue();
}
private static final double[] testValues = new double[] {
0.9,
1.0,
1.1,
2.8,
2.9,
3.9,
4.0,
4.1,
5.9,
6.0,
6.1,
6.4,
6.5,
6.6,
9.9,
10.0,
10.1
};
public static void main(String[] args) {
for (double d : testValues) {
System.out.println(d + " " + mappedValue(m, d));
}
}
}
@martiell
Copy link
Author

0.9 null
1.0 A
1.1 A
2.8 A
2.9 A
3.9 null
4.0 B
4.1 B
5.9 B
6.0 B
6.1 null
6.4 null
6.5 C
6.6 C
9.9 C
10.0 C
10.1 null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment