java Collection中的排序问题
这里讨论list、set、map的排序,包括按照map的value进行排序。
1)list排序
list排序可以直接采用Collections的sort方法,也可以使用Arrays的sort方法,归根结底Collections就是调用Arrays的sort方法。
public static <T> void sort(List<T> list, Comparator<? super T> c) { Object[] a = list.toArray(); Arrays.sort(a, (Comparator)c); ListIterator i = list.listIterator(); for (int j=0; j<a.length; j++) { i.next(); i.set(a[j]); } } |
如果是自定义对象,需要实现Comparable接口使得对象自身就有“比较”的功能,当然我们也可以在外部使用Comparator来规定其排序。
例如:
package com.fox;/** * @author huangfox * @data 2012-7-5 * @email huangfox009@126.com * @desc */public class User implements Comparable<User> { private String name; private int age; public User() { } public User(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "name:" + name + ",age:" + age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int compareTo(User o) { if (o.age < this.age) return 1; else if (o.age > this.age) return -1; else return 0; } /** * @param args */ public static void main(String[] args) { User u1 = new User("fox", 11); User u2 = new User("fox2", 21); System.out.println(u2.compareTo(u1)); }} |
排序:
// List<User> us = new ArrayList<User>(); List<User> us = new LinkedList<User>(); us.add(new User("f5", 12)); us.add(new User("f2", 22)); us.add(new User("f3", 2)); us.add(new User("f4", 14)); us.add(new User("f5", 32)); us.add(new User("f4", 12)); us.add(new User("f7", 17)); us.add(new User("f8", 52)); System.out.println(us.toString()); long bt = System.nanoTime(); Collections.sort(us, new Comparator<User>() { @Override public int compare(User o1, User o2) { if (o1.getAge() < o2.getAge()) return -1; else if (o1.getAge() > o2.getAge()) return 1; else return o1.getName().compareTo(o2.getName()); } }); long et = System.nanoTime(); System.out.println(et - bt); System.out.println(us.toString()); |
当然这里可以直接Collections.sort(us),这里用Comparator对User自身的比较方法compareTo做了一点点优化(对相同年龄的人根据用户名排序,String的排序)。
简单提一下,Arrays的排序采用的是插入排序和归并排序,当数组长度较小时直接插入排序。
2)set排序
set包括HashSet和TreeSet,HashSet是基于HashMap的,TreeSet是基于TreeMap的。
TreeMap是用红黑树实现,天然就具有排序功能,“天然就具有排序功能”是指它拥有升序、降序的迭代器。
那么HashSet怎么排序呢?我们可以将HashSet转成List,然后用List进行排序。
例如:
Set<User> us = new HashSet<User>(); // Set<User> us = new TreeSet<User>(); // Set<User> us = new TreeSet<User>(new Comparator<User>() { // // @Override // public int compare(User o1, User o2) { // if (o1.getAge() < o2.getAge()) // return -1; // else if (o1.getAge() > o2.getAge()) // return 1; // else // return o1.getName().compareTo(o2.getName()); // } // }); us.add(new User("f5", 12)); us.add(new User("f2", 22)); us.add(new User("f3", 2)); us.add(new User("f4", 14)); us.add(new User("f5", 32)); us.add(new User("f4", 12)); us.add(new User("f7", 17)); us.add(new User("f8", 52)); // set -> array List<User> list = new ArrayList<User>(us); System.out.println(list); Collections.sort(list); System.out.println(list); |
也可以将HashSet转换成数组用Arrays排序。
3)map排序
map包括HashMap和TreeMap,上面已经提过,TreeMap用红黑树实现,天然具有排序功能。
那么HashMap怎么按“key”排序呢?方法很简单,用HashMap来构造一个TreeMap。
Map<String, Integer> us = new HashMap<String, Integer>(); // Map<String, Integer> us = new TreeMap<String, Integer>(); us.put("f1", 12); us.put("f2", 13); us.put("f5", 22); us.put("f4", 42); us.put("f3", 15); us.put("f8", 21); us.put("f6", 123); us.put("f7", 1); us.put("f9", 19); System.out.println(us.toString()); System.out.println(new TreeMap<String, Integer>(us)); |
怎么按照“value”进行排序?
// 按照value排序 Set<Entry<String, Integer>> ks = us.entrySet(); List<Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>( ks); Collections.sort(list, new Comparator<Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { if (o1.getValue() < o2.getValue()) return -1; else if (o1.getValue() > o2.getValue()) return 1; return 0; } }); System.out.println(list); |
将map的Entry提出成set结构,然后将set转成list,最后按照list进行排序。
java Collection中的排序问题的更多相关文章
- 【Java心得总结六】Java容器中——Collection
在[Java心得总结五]Java容器上——容器初探这篇博文中,我对Java容器类库从一个整体的偏向于宏观的角度初步认识了Java容器类库.而在这篇博文中,我想着重对容器类库中的Collection容器 ...
- Java 8中Collection转为Map的方法
Java 8中java.util.stream.Collectors提供了几个方法可用于把Collection转为Map结构,本文记录了个人对其中三个的理解. Method Return Type g ...
- Java开发中的23种设计模式详解
[放弃了原文访问者模式的Demo,自己写了一个新使用场景的Demo,加上了自己的理解] [源码地址:https://github.com/leon66666/DesignPattern] 一.设计模式 ...
- Java开发中的23种设计模式详解(转)
设计模式(Design Patterns) ——可复用面向对象软件的基础 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了 ...
- Java Collection开发技巧
Java Collection(集合) 集合中的一些技巧: 通过Collections类的静态方法,可以对集合进行一些操作 1 java.util.List<Integer> number ...
- 详解Java 8中Stream类型的“懒”加载
在进入正题之前,我们需要先引入Java 8中Stream类型的两个很重要的操作: 中间和终结操作(Intermediate and Terminal Operation) Stream类型有两种类型的 ...
- Java 8中一些常用的全新的函数式接口
这一篇属于菜鸟级博客,只是介绍了一些在Java 8中新出现的一些很有用的接口,通过一些简单的例子加以说明,没有深入地阐述. 函数式接口 什么是函数式接口? 函数式接口,@FunctionalInter ...
- Java Collection Framework概述
文章出自:听云博客 Collection概述 Java collection是java提供的工具包,包含了常用的数据结构:集合.链表.队列.栈.数组.映射等. Java集合主要可以划分为4个部分:Li ...
- java开发中的23中设计模式详解--大话设计模式
设计模式(Design Patterns) ——可复用面向对象软件的基础 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了 ...
随机推荐
- django: rest-framework的 分页和过滤
django: rest-framework的 分页和过滤 2018年06月28日 10:09:01 weixin_42359464 阅读数:136 标签: flaskrestframeworkdja ...
- c++(重载等号=操作为深拷贝)
// ConsoleApplication19.cpp : 定义控制台应用程序的入口点. // #pragma warning(disable:4996) #include "stdafx. ...
- atom markdown报错:AssertionError: html-pdf: Failed to load PhantomJS module.
今天安装markdown-pdf之后运行的时候报错: AssertionError: html-pdf: Failed to load PhantomJS module. You have to se ...
- Appium移动端自动化测试之应用操作详解(四)
应用操作篇 1.1).安装应用 desired_caps = { 'platformName': 'Android', 'platformVersion': '5.0.0.0', 'deviceNam ...
- Azure:Manage anonymous read access to containers and blobs
Grant anonymous users permissions to containers and blobs By default, a container and any blobs with ...
- ios7适配--隐藏status bar
//viewDidload if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) { // iOS 7 ...
- 状态压缩DP----HDU2809
状态压缩DP的一道较不错的入门题,第二次做这类问题,感觉不是很顺手,故记录下来. 题目的意思就是吕布战群雄,先给你6个数,分别是吕布的攻击值,防御值,生命值,升级后此三值各自的增量,然后是对手的个数n ...
- POJ3259 Wormholes(SPFA判断负环)
Description While exploring his many farms, Farmer John has discovered a number of amazing wormholes ...
- 用css画的一个图形 空心正方形+四边四色
div{ width: 100px; height: 100px; border: 100px solid black; border-left-color:darkcyan; border-righ ...
- 【C#】MVC+EF+LINQ 综合小项目
第一,创建数据库 create table category(id int primary key,name nvarchar(20)) create table news(id int primar ...