您的位置:首页 > 编程语言 > Java开发

Java List/HashSet/HashMap的排序

2013-07-19 11:16 441 查看
前言·:

在对Java无序类集合,如List(ArrayList/LinkedList)、HashSet(TreeSet有序)、HashMap等排序时,Java中一个公共的类Collections,提供了对Java集合排序等很好的方法sort。 但是有一个要求是sort方法的参数为<List list> 或<List list, Comparator<? super T> c>,即排序对象要求必须是List类型。

sort 方法的参数必须为List 的原因是,只有List可以定义排序的方法,让List中的元素改变在构建List时原始的相对位置(初始构建时,元素相对位置即为元素初始加入顺序)。HashSet、HashMap 在构建时,初始加入的元素已经按照元素的hashCode()方法的定义排好序。所以这里所说的HashSet 排序 和 HashMap 排序是指:将其中的元素导出到另一个集合中,对该载体集合排序。排序之后,原HashSet 和 HashMap 中元素顺序没有变。

故而对Java无序类集合的排序问题,基本思路就是:将HashSet 或 HashMap 中的元素取出放入 List 中,对List 用 Collections.sort() 方法排序,之后输出排序后List中的元素,即为对Set/Map 中元素排序后的结果。注意HashSet、HashMap 中元素位置没有改变,依然只和 初始构建时,元素本身自定义的hashCode() 方法有关

对HashSet 等可以重写元素类中的hashCode 等方法,实现自己想定义的排序机制。参考 HashSet,LinkedHashSet,TreeSet的内部排序

Java集合框架之小结 由Java中的Set,List,Map引出的排序技巧

【源码前了无秘密】:Java 集合类源码:Thinking in Java之集合相关整理(源码分析) Java集合类源码分析汇总

Test例子:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

public class Test {
public static void main(String[] args){
ArrayList<String> listTest = new ArrayList<String>();
listTest.add("bbc");
listTest.add("abc");
listTest.add("acb");

HashSet<String> setTest = new HashSet<String>();
setTest.add("bbc");
setTest.add("abc");
setTest.add("acb");
System.out.println("HashSet BeforeSort:");
for(String s : setTest)
System.out.println(s);

HashMap<String, Integer> mapTest = new HashMap<String, Integer>();
mapTest.put("bbc", 1);
mapTest.put("abc", 2);
mapTest.put("acb", 3);
System.out.println("HashMap BeforeSort:");
for(Map.Entry<String, Integer> entry : mapTest.entrySet())
System.out.println(entry.getKey() + " " + entry.getValue());

/*
* List
*/
Collections.sort(listTest);
Iterator<String> list_iter = listTest.iterator();
while(list_iter.hasNext())
System.out.println(list_iter.next());

/*
* Set
*/
LinkedList<String> setSort = new LinkedList<String>(setTest);
//Collections.sort(setSort);
Comparator<String> setComp = Collections.reverseOrder();
Collections.sort(setSort, setComp);
/*LinkedList<String> setSort = new LinkedList<String>();
for(String s : setTest)
setSort.add(s);*/
for(String s : setTest)
System.out.println(s);
for(String s : setSort)
System.out.println(s);

/*
* Map
*/
LinkedList<String> mapSort = new LinkedList<String>();
mapSort.addAll(mapTest.keySet());
//Collections.sort(mapSort);
Comparator<String> mapComp = Collections.reverseOrder();
Collections.sort(mapSort, mapComp);
for(Map.Entry<String, Integer> entry : mapTest.entrySet())
System.out.println(entry.getKey() + " " + entry.getValue());
for(final Iterator<String> map_iter= mapSort.iterator(); map_iter.hasNext();)
System.out.println(map_iter.next());
/*
LinkedList<Map.Entry<String, Integer>> mapEntry = new LinkedList<Map.Entry<String,Integer>>();
mapEntry.addAll(mapTest.entrySet());
Collections.sort(mapEntry, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b){
if(a.getValue() > b.getValue())
return -1;
else
return 1;
}
});

for(Map.Entry<String, Integer> entry : mapEntry)
System.out.println(entry.getKey() + " " +entry.getValue());
for(Map.Entry<String, Integer> entry : mapTest.entrySet())
System.out.println(entry.getKey() + " " + entry.getValue());*/
}
}


输出结果:

HashSet BeforeSort:
abc
acb
bbc
HashMap BeforeSort:
abc 2
acb 3
bbc 1
//List AfterSort
abc
acb
bbc
//HashSet AfterSort
abc
acb
bbc
//setSort AfterSort (setSort is means HashSet to LinkedList)
bbc
acb
abc
//HashMap AfterSort
abc 2
acb 3
bbc 1
//mapSort AfterSort (mapSort is means HashMap to LinkedList)
bbc
acb
abc


参考原文《HashMap的排序》地址:http://hi.baidu.com/wenzheng38/item/0c2ed5c52303127388ad9efd 内容如下:

一、按key值排序

假设HashMap存储的键-值对为(String,Integer),按key排序可以调用JDK函数sort(默认的按字典升序):

Set<String> keySet = map.keySet();

Collections.sort(keySet);

for(Iterator<String> ite = keySet.iterator(); ite.hasNext();) {

String temp = ite.next();

System.out.println("key-value: "+temp+","+map.getValue(temp);

}

如果想要按字典的降序排列,则需改写sort方法里面的比较器Comparator:

Collections.sort(keySet, new Comparator() {

public int compare(Object o1, Object o2) {

if(Integer.parseInt(o1.toString())>Integer.parseInt(o2.toString())

return 1;

if(Integer.parseInt(o1.toString())==Integer.parseInt(o2.toString())

return 0;

else

return -1;

}

});

二、按value值排序

1)方法一:用两个list链表实现

List<String> keyList = new LinkedList<String>();

keyList.addAll(map.keySet());

List<Integer> valueList = new LinkedList<Integer>();

valueList.addAll(map.values());

for(int i=0; i<valueList.size(); i++)

for(int j=i+1; j<valueList.size(); j++) {

if(valueList.get(j)>valueList.get(i)) {

valueList.set(j, valueList.get(i));

valueList.set(i, valueList.get(j));

//同样调整对应的key值

keyList.set(j, keyList.get(i));

keyList.set(i, kyeList.get(j));

}

然后依次把key值和对应value值重新装入HashMap即可。

2)方法二:改写JDK提供的Comparator接口方法compare

List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>();

list.addAll(map.entrySet());

Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {

public int compare(Map.Entry obj1, Map.Entry obj2) {//从高往低排序

if(Integer.parseInt(obj1.getValue().toString())<Integer.parseInt(obj2.getValue().toString()))

return 1;

if(Integer.parseInt(obj1.getValue().toString())==Integer.parseInt(obj2.getValue().toString()))

return 0;

else

return -1;

}

});

for(Iterator<Map.Entry<String, Integer>> ite = list.iterator(); ite.hasNext();) {

Map.Entry<String, Integer> map = ite.next();

System.out.println("key-value: " + map.getKey() + "," + map.getValue());

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: