1.简单示例

sort方法的使用非常的简单明了,下面的例子中,先定义一个比较Dog大小的Comparator,然后将其实例对象作为参数传给sort方法,通过此示例,你应该能够快速掌握Arrays.sort()的使用方法。

import java.util.Arrays;
import java.util.Comparator;
class Dog{
int size;
public Dog(int s){
size = s;
}
} class DogSizeComparator implements Comparator<Dog>{
@Override
public int compare(Dog o1, Dog o2) {
return o1.size - o2.size;
}
} public class ArraySort {
public static void main(String[] args) {
Dog d1 = new Dog(2);
Dog d2 = new Dog(1);
Dog d3 = new Dog(3);
Dog[] dogArray = {d1, d2, d3};
printDogs(dogArray); //或者采用匿名内部类
/**
Arrays.sort(dogArray, new Comparator<Dog>(){
@Override
public int compare(Dog o1, Dog o2) {
return o1.size - o2.size;
}
});
*/
Arrays.sort(dogArray, new DogSizeComparator());
printDogs(dogArray);
} public static void printDogs(Dog[] dogs)
for(Dog d: dogs) System.out.print(d.size + " " );
System.out.println();
}
}

2.使用策略模式

这是策略模式(Strategy pattern)的一个完美又简洁的示例,值得一提的是为什么这种场景下适合使用策略模式。

总体来说,策略模式允许在程序执行时选择不同的算法。比如在排序时,传入不同的比较器(Comparator),就采用不同的算法。

根据上面的例子,假设你想要根据Dog的重量来进行排序,可以像下面这样,创建一个新的比较器来进行排序:

class Dog{
int size;
int weight; public Dog(int s,int w){
size = s;
weight = w;
}
} class DogSizeComparator implements Comparator<Dog>{ @Override
public int compare(Dogo1,Dogo2){
return o1.size - o2.size;
}
} class DogWeightComparator implements Comparator<Dog>{ @Override
public int compare(Dogo1,Dogo2){
return o1.weight - o2.weight;
}
} public class ArraySort{ public static void main(String[] args){
Dog d1 = new Dog(2,50);
Dog d2 = new Dog(1,30);
Dog d3 = new Dog(3,40); Dog[] dogArray = {d1,d2,d3};
printDogs(dogArray); Arrays.sort(dogArray, new DogSizeComparator());
printDogs(dogArray); Arrays.sort(dogArray,new DogWeightComparator());
printDogs(dogArray);
} public static void printDogs(Dog[]dogs){
for(Dog d : dogs) System.out.print("size=" + d.size + "weight=" + d.weight + "");
System.out.println();
}
}

Comparator是一个接口,所以sort方法中可以传入任意实现了此接口的类的实例,这就是策略模式的主要思想。

3.为何使用"super"

如果使用“Comparator < T > c”那是很简单易懂的,但是sort的第2个参数里面的< ? super T >意味着比较器所接受的类型可以是T或者它的超类,为什么是超类呢? 答案是:这允许使用同一个比较器对不同的子类对象进行比较。在下面的示例中很明显地演示了这一点:

import java.util.Arrays;
import java.util.Comparator; class Animal{
int size;
} class Dog extends Animal{
public Dog(int s){
size = s;
}
} class Cat extends Animal{
public Cat(int s){
size= s;
}
} class AnimalSizeComparator implements Comparator<Animal>{
@Override
public int compare(Animal o1, Animal o2) {
return o1.size - o2.size;
}
//in this way, all sub classes of Animal can use this comparator.
} public class ArraySort { public static void main(String[] args) {
Dog d1 = new Dog(2);
Dog d2 = new Dog(1);
Dog d3 = new Dog(3);
Dog[] dogArray = {d1, d2, d3};
printDogs(dogArray); Arrays.sort(dogArray, new AnimalSizeComparator());
printDogs(dogArray); System.out.println(); //when you have an array of Cat, same Comparator can be used.
Cat c1 = new Cat(2);
Cat c2 = new Cat(1);
Cat c3 = new Cat(3); Cat[] catArray = {c1, c2, c3};
printDogs(catArray); Arrays.sort(catArray, new AnimalSizeComparator());
printDogs(catArray);
} public static void printDogs(Animal[] animals){
for(Animal a: animals) System.out.print("size="+a.size + " "); System.out.println();
}
}

4.Collections sort(List< T >,Comparator<? super T>) 用法

public class Student implements Comparable<Student> {

    String name;
int age; public Student(String name, int age) {
this.name = name;
this.age = age;
} @Override
public String toString() {
return name + ":" + age;
} @Override
public int compareTo(Student o) {
return Comparators.NAME.compare(this, o);
} public static class Comparators { public static Comparator<Student> NAME = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.name.compareTo(o2.name);
}
};
public static Comparator<Student> AGE = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.age - o2.age;
}
};
public static Comparator<Student> NAMEANDAGE = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int i = o1.name.compareTo(o2.name);
if (i == 0) {
i = o1.age - o2.age;
}
return i;
}
};
}
}
//用法
List<Student> studentList = new LinkedList<>();
Collections.sort(studentList, Student.Comparators.AGE);

5.Sorting HashMap by values(HashMap值排序)

package leetcode;

/**
* Created by slyuan on 17-4-18.
*/
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; public class SortMapByValue {
public static boolean ASC = true;
public static boolean DESC = false; public static void main(String[] args) { // Creating dummy unsorted map
Map<String, Integer> unsortMap = new HashMap<String, Integer>();
unsortMap.put("B", 55);
unsortMap.put("A", 80);
unsortMap.put("D", 20);
unsortMap.put("C", 70); System.out.println("Before sorting......");
printMap(unsortMap); System.out.println("After sorting ascending order......");
Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
printMap(sortedMapAsc); System.out.println("After sorting descindeng order......");
Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
printMap(sortedMapDesc); } private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order) { List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet()); // Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
if (order) {
return o1.getValue().compareTo(o2.getValue());
} else {
return o2.getValue().compareTo(o1.getValue());
}
}
}); // Maintaining insertion order with the help of LinkedList
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
} return sortedMap;
} public static void printMap(Map<String, Integer> map) {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
}
}
}
   //另一种实现方式
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ) {
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>( map.entrySet() );
Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 ) {
return (o1.getValue()).compareTo( o2.getValue() );
}
} ); Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
result.put( entry.getKey(), entry.getValue() );
}
return result;
}

5.Sorting HashMap by key

Using the TreeMap you can sort the Map, 默认情况下,TreeMap对key进行升序排序

Map<String, String> unsortMap = new HashMap<String, String>();
Map<String, String> treeMap = new TreeMap<String, String>(unsortMap);
for (String str : treeMap.keySet()) {
System.out.println(str);
}

注意:正常情况下Map是不可以使用Collections.sort()方法进行排序的,不过可以将Map转换成list之后再进行排序。

List<Entry<String,Integer>> list = new LinkedList<>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) {
return e1.getKey().compareTo(e2.getKey());
}
});

Java中Arrays.sort()和Collections.sort()的更多相关文章

  1. Arrays.sort 与 Collections.sort

    代码如下: package com.wangzhu.arrays; import java.util.Arrays; import java.util.Collections; public clas ...

  2. 48- java Arrays.sort和collections.sort()再次总结

    今天又碰到一个新BUG,记下来. 一直报空指针异常,我就很奇怪了,怎么就空指针了呢,我输出时,也能输出东西呀. 原来Arrays.sort() 和 Collections.sort() 都是对整个数组 ...

  3. Arrays.sort和Collections.sort实现原理解析

    Arrays.sort和Collections.sort实现原理解析 1.使用 排序 2.原理 事实上Collections.sort方法底层就是调用的array.sort方法,而且不论是Collec ...

  4. sort()排序 collections.sort();

    1.main方法: public class Test { public static void main(String[] args) { /** * * sort()方法详解 * 1.Collec ...

  5. 关于Java中Arrays.sort()方法TLE

    最近一直在练用Java写题,今天无意发现一道很简单的二分题(链接),我一开始是直接开int[]数组调用Arrays.sort()去排序,没想到TLE了,原来是因为jdk中对于int[]的排序是使用快速 ...

  6. 39-java中Arrays.sort 和 collections.sort()总结

    总结一下java 中的两种排序工具: Arrays.sort() : 主要针对 数组类型排序,如果数组里面的元素是对象,要按对象属性排序的话,需要重写 Comparator() 函数,重写里面的  i ...

  7. 5.4 集合的排序(Java学习笔记)(Collections.sort(),及Arrays.sort()底层分析)

    1.Comparable接口 这个接口顾名思义就是用于排序的,如果要对某些对象进行排序,那么该对象所在的类必须实现 Comparabld接口.Comparable接口只有一个方法CompareTo() ...

  8. java中Arrays.sort()对二位数组进行排序

    int [][]a = new int [5][2]; //定义一个二维数组,其中所包含的一维数组具有两个元素 对于一个已定义的二位数组a经行如下规则排序,首先按照每一个对应的一维数组第一个元素进行升 ...

  9. 集合(一)-Java中Arrays.sort()自定义数组的升序和降序排序

    默认升序 package peng; import java.util.Arrays;  public class Testexample { public static void main(Stri ...

随机推荐

  1. Microsoft SQL Server JDBC 驱动程序支持矩阵

    本页包含 Microsoft SQL Server JDBC 驱动程序的支持矩阵和支持生命周期策略. Microsoft JDBC 驱动程序支持生命周期矩阵和策略 Microsoft 支持生命周期 ( ...

  2. 009android初级篇之APP中使用系统相机相册等集成应用

    android应用中使用相机功能,大致有两种方式实现: 直接调用系统内部的相机程序,显示的也是系统预设的界面(简单,只有简单的拍照功能): 自己去implement一个相机程序(不难,较具备弹性,但相 ...

  3. 代码备份:按模式划分椭圆轨迹渐变matlab

    x=sqrt(a^*(-y^/b^)); r=ceil(+*y); x=ceil(x); I(m/,m/+x)=+*y; elseif r== I(m/::m/+,m/+x::m/++x)=+*y; ...

  4. python3----split and join

    s = "I am fine" s = s.split(" ") print(s) print("%".join(s)) results: ...

  5. SSL证书的生成

    openssl工具下载路径:链接:https://pan.baidu.com/s/1o0-s8OplHZt55Cio2HmjVA 密码:u759 1.使用openssl工具生成一个RSA秘钥      ...

  6. HUST 1354 - Rubiks (DP)

    1354 - Rubiks 时间限制:1秒 内存限制:64兆 452 次提交 102 次通过 题目描述 Isun is a genius. Not only he is an expert in al ...

  7. JS和C# 里的闭包及闭包在事件中的使用

    在Javascript世界里,无所不用闭包及自定义事件, 自定义事件其实也是事先定义好一种规则 ,当触发者被响应后执行的一段回调.下面看个例子 function dothing(callBack){ ...

  8. python系列三:python3运算符

    '''python 没有自增运算符python 中,变量是以内容为基准而不是像 c 中以变量名为基准,所以只要你的数字内容是5,不管你起什么名字,这个变量的 ID 是相同的,同时也就说明了 pytho ...

  9. 约束、自定义异常、hashlib模块、logging日志模块

    一.约束(重要***) 1.首先我们来说一下java和c#中的一些知识,学过java的人应该知道,java中除了有类和对象之外,还有接口类型,java规定,接口中不允许在方法内部写代码,只能约束继承它 ...

  10. 0201-开始使用Spring Cloud实战微服务准备工作

    1.Spring Cloud是什么 基于spring boot,之上快速构建分布式系统的工具集 服务注册和发现[eureka.Consul.Zookeeper].服务负载均衡[Ribbon,feign ...