Java List/HashSet/HashMap的排序
在对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() 方法有关。
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
一、按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());
}
Java List/HashSet/HashMap的排序的更多相关文章
- java 中对hashmap进行排序
public class HashMapSort { public static void main(String[] args) { HashMap<Integer, Student> ...
- C++中的set和java的hashset有何区别?
以前对C++的STL容器烂熟于心,两年没碰过C++了,现在已经很生疏了.工作原因转战java,对java的容器不甚了解,特别是每看到一种容器,不由自主地拿起和C++对比.C++中的set和java的h ...
- Java集合 -- HashSet 和 HashMap
HashSet 集合 HashMap 集合 HashSet集合 1.1 Set 接口的特点 Set体系的集合: A:存入集合的顺序和取出集合的顺序不一致 B:没有索引 C:存入集合的元素没有重复 1. ...
- java 中遍历hashmap 和hashset 的方法
一.java中遍历hashmap: for (Map.Entry<String, Integer> entry : tempMap.entrySet()) { String ...
- java该HashTable,HashMap和HashSet
同一时候我们也对HashSet和HashMap的核心方法hashcode进行了具体解释,见<探索equals()和hashCode()方法>. 万事俱备,那么以下我们就对基于hash算法的 ...
- 【java基础】java集合之HashTable,HashSet,HashMap
[一]HashSet (1)HashSet内部维护的是一个HashMap,具体原理见java集合之HashMap [二]HashTable (1)HashTable内部维护的是一个Entry的数组.E ...
- Java中HashSet和HashMap
Set中存储元素为什么不重复(即使hashCode相同)? HashSet中存放自定义类型元素时候,需要重写对象中的hashCode方法和equals方法, HashSet中存放自定义类型元素时候,需 ...
- HashTable, HashSet, HashMap的区别
HashTable, HashSet, HashMap的区别 hash是一种很常见也很重要的数据结构,是用hash函数根据键值(key)计算出存储地址,以便直接访问.由完美hash函数(即键值 ...
- JAVA Collections工具类sort()排序方法
主要分析内容: 一.Collections工具类两种sort()方法 二.示例 一.Collections工具类两种sort()方法 格式一: public static <T extends ...
随机推荐
- linux设置iptables防火墙的详细步骤(centos防火墙设置方法)
CentOS系统也是基于linux中的它的防火墙其实就是iptables了,下面我来介绍在CentOS防火墙iptables的配置教程,希望此教程对各位朋友会有所帮助. iptables是与Lin ...
- 【转载】Docker 经验之谈
本文来源:Ghostcloud原创 对于用户来说,可能一开始在不了解的情况下会对容器报以拒绝的态度,但是在尝到容器的甜头.体验到它的强大性能之后,相信大家最终是无法抵挡其魅力的.容器技术能够解 ...
- Koa 框架整理
学习交流 Koa使用了ES6规范的generator和异步编程是一个更轻量级Web开发的框架,Koa 的先天优势在于 generator.由于是我个人的分享交流,所以Node基础.ES6标准.Web开 ...
- MySql 链接字符串
MySql连接字符串总结 1.本地数据库连接 <connectionStrings> <add name="ConnectionString" ...
- string hashcode 解读
偶尔看到string hashcode方法如下 public int hashCode() { int h = hash; if (h == 0 && value.length > ...
- uva140-暴力枚举
题意:任意一个点都至少有一个点与其相连接,所有的点可以进行任意排列,总排列数为n!. 一个点带宽定义与它相连的点的最远距离,一个排列的带宽定义为,点中最大的带宽,找出带宽最小的那个排列,有多组,输出字 ...
- ssh连接失败,提示 WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
[root@iZ2ze4kh1rvftq4cevdfjwZ ~]# ssh IP @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ...
- python入门-异常
1 报错的例子 print(5/0) 2跳过报错的例子 try: print(5/0) except ZeroDivisionError: print("You can't divide b ...
- Springboot spring data jpa 多数据源的配置01
Springboot spring data jpa 多数据源的配置 (说明:这只是引入了多个数据源,他们各自管理各自的事务,并没有实现统一的事务控制) 例: user数据库 global 数据库 ...
- django-allauth 使用
参考: http://www.honkerzhou.com/post/3/ https://www.jianshu.com/p/41335d861a8d https://django-allauth. ...