JAVA 自带的Map接口是没有排序功能。即使你按照一定的顺序输入,但是输出结果也往往是随机的,对一些特殊的应用很不爽。这时候,可以使用TreeMap类进行转换一下就可以了。如果需要排序的功能,最好在new Map对象的时候,使用TreeMap. 但是如果对已经存在的Map进行按值排序,则需进行转换一下。
代码如下:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class ArrayTest
{
public static void main(String[] args)
{
Map<String, String> yourMap = new HashMap<String, String>();
yourMap.put("3", "c");
yourMap.put("4", "d");
yourMap.put("1", "a");
yourMap.put("2", "b");
Map<String, Object> map = new LinkedHashMap<String, Object>();
List<String> keyList = new ArrayList<String>(yourMap.keySet());
List<String> valueList = new ArrayList<String>(yourMap.values());
Set<String> sortedSet = new TreeSet<String>(valueList);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
for (int i = 0; i < size; i++) {
map.put(keyList.get(valueList.indexOf(sortedArray[i])), sortedArray[i]);
}
Set ref = map.keySet();
Iterator it = ref.iterator();
while (it.hasNext()) {
String i = (String) it.next();
System.out.println(i+":"+map.get(i));
}
}
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class ArrayTest
{
public static void main(String[] args)
{
Map<String, String> yourMap = new HashMap<String, String>();
yourMap.put("3", "c");
yourMap.put("4", "d");
yourMap.put("1", "a");
yourMap.put("2", "b");
Map<String, Object> map = new LinkedHashMap<String, Object>();
List<String> keyList = new ArrayList<String>(yourMap.keySet());
List<String> valueList = new ArrayList<String>(yourMap.values());
Set<String> sortedSet = new TreeSet<String>(valueList);
Object[] sortedArray = sortedSet.toArray();
int size = sortedArray.length;
for (int i = 0; i < size; i++) {
map.put(keyList.get(valueList.indexOf(sortedArray[i])), sortedArray[i]);
}
Set ref = map.keySet();
Iterator it = ref.iterator();
while (it.hasNext()) {
String i = (String) it.next();
System.out.println(i+":"+map.get(i));
}
}
}
本文转自 randy_shandong 51CTO博客,原文链接:http://blog.51cto.com/dba10g/290265,如需转载请自行联系原作者