RT
运行结果
- ========================== TEST 1 (sort by key)
-
input = {83=0, 85=1, 33=2, 92=3, 57=4, 26=5, 56=6, 25=7, 22=8, 47=9}
-
result = {22=8, 25=7, 26=5, 33=2, 47=9, 56=6, 57=4, 83=0, 85=1, 92=3}
-
-
========================== TEST 2 (sort by value)
-
input = {0=83, 1=85, 2=33, 3=92, 4=57, 5=26, 6=56, 7=25, 8=22, 9=47}
-
result = {8=22, 7=25, 5=26, 2=33, 9=47, 6=56, 4=57, 0=83, 1=85, 3=92}
TestSortMapByValue.java
- import java.util.Collections;
-
import java.util.Comparator;
-
import java.util.Iterator;
-
import java.util.LinkedHashMap;
-
import java.util.LinkedList;
-
import java.util.List;
-
import java.util.Map;
-
import java.util.Random;
-
import java.util.TreeMap;
-
import java.util.Map.Entry;
-
-
/**
-
* 将Map按照value进行排序。
-
*
-
* @author btpka3@163.com
-
*/
-
public class TestSortMapByValue {
-
-
/**
-
* @param args
-
*/
-
public static void main(String[] args) {
-
test01();
-
test02();
-
}
-
-
/**
-
* 测试使用按照Key排序的Map。
-
*
-
* 使用JDK提供的TreeMap即可按照key进行排序。
-
* 使用JDK提供的LinkedHashMap即可保留插入时的先后顺序。
-
*/
-
public static void test01() {
-
System.out.println("========================== TEST 1 (sort by key)");
-
Map<String, Integer> input = new LinkedHashMap<String, Integer>();
-
-
Random r = new Random(System.currentTimeMillis());
-
for (int i = 0; i < 10; i++) {
-
String k = Integer.toString(Math.abs(r.nextInt()) % 90 + 10);
-
input.put(k, i);
-
}
-
Map<String, Integer> output = new TreeMap<String, Integer>(input);
-
-
System.out.println("input = " + input);
-
System.out.println("result = " + output);
-
System.out.println();
-
}
-
-
/**
-
* 测试将Map按照Value排序。
-
*/
-
public static void test02() {
-
System.out.println("========================== TEST 2 (sort by value)");
-
Map<String, Integer> input = new LinkedHashMap<String, Integer>();
-
-
Random r = new Random(System.currentTimeMillis());
-
for (int i = 0; i < 10; i++) {
-
int v = Math.abs(r.nextInt()) % 90 + 10;
-
input.put(i + "", v);
-
}
-
Map<String, Integer> output = sortByValue(input);
-
System.out.println("input = " + input);
-
System.out.println("result = " + output);
-
System.out.println();
-
}
-
-
// 参考:
-
public static <K, V extends Comparable<V>> Map<K, V> sortByValue(
-
Map<K, V> map) {
-
List<Entry<K, V>> list = new LinkedList<Entry<K, V>>(map.entrySet());
-
Collections.sort(list, new Comparator<Entry<K, V>>() {
-
public int compare(Entry<K, V> o1, Entry<K, V> o2) {
-
-
Comparable<V> v1 = o1.getValue();
-
V v2 = o2.getValue();
-
if (v1 == null) {
-
if (v2 == null) {
-
return 0;
-
} else {
-
return -1;
-
}
-
} else {
-
if (v2 == null) {
-
return 1;
-
} else {
-
return v1.compareTo(v2);
-
}
-
}
-
}
-
});
-
Map<K, V> result = new LinkedHashMap<K, V>();
-
Iterator<Entry<K, V>> it = list.iterator();
-
while (it.hasNext()) {
-
Entry<K, V> entry = it.next();
-
result.put(entry.getKey(), entry.getValue());
-
}
-
return result;
-
}
-
}
阅读(1337) | 评论(0) | 转发(0) |