Created
January 25, 2010 07:37
-
-
Save tsuna/285706 to your computer and use it in GitHub Desktop.
This file contains 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.Comparator; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.TreeSet; | |
public class t { | |
static public void main(String[] args) { | |
HashMap<String, Integer> hm = new HashMap<String, Integer>(); | |
hm.put("answer", 42); | |
hm.put("none", 0); | |
hm.put("pastis", 51); | |
hm.put("vodka", 40); | |
TreeSet<Map.Entry<String, Integer>> kvs = new TreeSet<Map.Entry<String, Integer>>( | |
new Comparator() { | |
public int compare(Object a, Object b) { | |
Integer diff = (((Map.Entry<String, Integer>) b).getValue() | |
- ((Map.Entry<String, Integer>) a).getValue()); | |
return diff.intValue(); | |
} | |
}); | |
kvs.addAll(hm.entrySet()); | |
if (kvs.size() != hm.size()) | |
throw new RuntimeException(String.format("OMG %d != %d", kvs.size(), hm.size())); | |
for (Map.Entry<String, Integer> kv : kvs) { | |
System.out.println("key="+kv.getKey()+" value="+kv.getValue()); | |
} | |
} | |
} | |
/* | |
$ javac -Xlint t.java && java t | |
t.java:132: warning: [unchecked] unchecked cast | |
found : java.lang.Object | |
required: java.util.Map.Entry<java.lang.String,java.lang.Integer> | |
Integer diff = (((Map.Entry<String, Integer>) b).getValue() | |
^ | |
t.java:133: warning: [unchecked] unchecked cast | |
found : java.lang.Object | |
required: java.util.Map.Entry<java.lang.String,java.lang.Integer> | |
- ((Map.Entry<String, Integer>) a).getValue()); | |
^ | |
t.java:130: warning: [unchecked] unchecked conversion | |
found : <anonymous java.util.Comparator> | |
required: java.util.Comparator<? super java.util.Map.Entry<java.lang.String,java.lang.Integer>> | |
new Comparator() { | |
^ | |
3 warnings | |
key=pastis value=51 | |
key=answer value=42 | |
key=vodka value=40 | |
key=none value=0 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment