-
-
Save deveshmittal/dc74e96eec063b14a1d1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment