java Comparator 实现不一样的排序

程序员面试宝典中,大家应该都看过各种排序方法:

冒泡

选择

插入

快速

堆排序

等等..

这些针对的都是简单的数据类型,比如数值型int类型,当遇到实际情况中的复杂排序,比如对一个公司的员工,依据姓名,年龄,性别等不同的因素综合排序的情形,用上面的排序方法,将无法实现。但是不要害怕~java中有大神器:Comparator接口

我们来看下源码,简单的让你不知道该怎么做..

public interface Comparator<T> {
    /**
     * Compares its two arguments for order.  Returns a negative integer,
     * zero, or a positive integer as the first argument is less than, equal
     * to, or greater than the second.<p>
     *
     * In the foregoing description, the notation
     * <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical
     * <i>signum</i> function, which is defined to return one of <tt>-1</tt>,
     * <tt>0</tt>, or <tt>1</tt> according to whether the value of
     * <i>expression</i> is negative, zero or positive.<p>
     *
     * The implementor must ensure that <tt>sgn(compare(x, y)) ==
     * -sgn(compare(y, x))</tt> for all <tt>x</tt> and <tt>y</tt>.  (This
     * implies that <tt>compare(x, y)</tt> must throw an exception if and only
     * if <tt>compare(y, x)</tt> throws an exception.)<p>
     *
     * The implementor must also ensure that the relation is transitive:
     * <tt>((compare(x, y)>0) && (compare(y, z)>0))</tt> implies
     * <tt>compare(x, z)>0</tt>.<p>
     *
     * Finally, the implementor must ensure that <tt>compare(x, y)==0</tt>
     * implies that <tt>sgn(compare(x, z))==sgn(compare(y, z))</tt> for all
     * <tt>z</tt>.<p>
     *
     * It is generally the case, but <i>not</i> strictly required that
     * <tt>(compare(x, y)==0) == (x.equals(y))</tt>.  Generally speaking,
     * any comparator that violates this condition should clearly indicate
     * this fact.  The recommended language is "Note: this comparator
     * imposes orderings that are inconsistent with equals."
     *
     * @param o1 the first object to be compared.
     * @param o2 the second object to be compared.
     * @return a negative integer, zero, or a positive integer as the
     *         first argument is less than, equal to, or greater than the
     *         second.
     * @throws NullPointerException if an argument is null and this
     *         comparator does not permit null arguments
     * @throws ClassCastException if the arguments' types prevent them from
     *         being compared by this comparator.
     */
  <span style="font-size:18px;">  int compare(T o1, T o2);</span>

    /**
     * Indicates whether some other object is "equal to" this
     * comparator.  This method must obey the general contract of
     * {@link Object#equals(Object)}.  Additionally, this method can return
     * <tt>true</tt> <i>only</i> if the specified object is also a comparator
     * and it imposes the same ordering as this comparator.  Thus,
     * <code>comp1.equals(comp2)</code> implies that <tt>sgn(comp1.compare(o1,
     * o2))==sgn(comp2.compare(o1, o2))</tt> for every object reference
     * <tt>o1</tt> and <tt>o2</tt>.<p>
     *
     * Note that it is <i>always</i> safe <i>not</i> to override
     * <tt>Object.equals(Object)</tt>.  However, overriding this method may,
     * in some cases, improve performance by allowing programs to determine
     * that two distinct comparators impose the same order.
     *
     * @param   obj   the reference object with which to compare.
     * @return  <code>true</code> only if the specified object is also
     *          a comparator and it imposes the same ordering as this
     *          comparator.
     * @see Object#equals(Object)
     * @see Object#hashCode()
     */
<span style="font-size:18px;">    boolean equals(Object obj);</span>
}

就2个方法,那么实现复杂的排序,我们只要实现该接口中的compare接口就OK了。

具体代码如下:

package someTest;

import java.util.Comparator;

class Person {  

String firstname,lastname;
Boolean sex;
Integer age;  

public Person(String firstname,String lastname,Boolean sex,Integer age) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.sex = sex;
    this.age = age;
}
public String getFirstName() {
     return firstname;
   }  

   public String getLastName() {
     return lastname;
   }
   public Boolean getSex() {
      return sex;
    }  

    public Integer getAge() {
      return age;
    }  

//为了输入方便,重写了toString()
public String toString()
    {
      return firstname +" "+lastname+" "+(sex.booleanValue()?"男":"女")+" "+age;
    }
}
//end person  

public class CompareObject implements Comparator<Object> {
@Override
public int compare(Object o1, Object o2){
	        if (o1 instanceof String) {  

	        	return compareImp( (String) o1, (String) o2);  

	        }else if (o1 instanceof Integer) {  

	          return compareImp( (Integer) o1, (Integer) o2);  

	        }else if (o1 instanceof Boolean) {  

	        return compareImp( (Boolean) o1, (Boolean) o2);  

	        } else if (o1 instanceof Person) {  

	        return compareImp( (Person) o1, (Person) o2);  

	        }else {  //根据需要扩展compare函数
	          System.err.println("未找到合适的比较器");
	          return 1;
	        }
	      }
	//重载
  public int compareImp(String o1, String o2) {
	        String s1 = (String) o1;
	        String s2 = (String) o2;
	        int len1 = s1.length();
	        int len2 = s2.length();
	        int n = Math.min(len1, len2);
	        char v1[] = s1.toCharArray();
	        char v2[] = s2.toCharArray();
	        int pos = 0;  

	        while (n-- != 0) {
	          char c1 = v1[pos];
	          char c2 = v2[pos];
	          if (c1 != c2) {
	            return c1 - c2;
	          }
	          pos++;
	        }
	        return len1 - len2;
	      }
	//重载
 public int compareImp(Integer o1, Integer o2) {
	        int val1 = o1.intValue();
	        int val2 = o2.intValue();
	        return (val1 < val2 ? -1 : (val1 == val2 ? 0 : 1));  

	      }
 	//重载
 public int compareImp(Boolean o1, Boolean o2) {
	      return (o1.equals(o2)? 0 : (o1.booleanValue()==true?1:-1));
	     }  

 /*实体类的排序
  * 进行姓排序,谁的姓拼音靠前,谁就排前面。
  * 然后对名字进行排序。如果同名,女性排前头。
  * 如果名字和性别都相同,年龄小的排前头。
  * */
 //重载
public int compareImp(Person o1, Person o2) {  

	        String firstname1 = o1.getFirstName();
	        String firstname2 = o2.getFirstName(); 

	        String lastname1 = o1.getLastName();
	        String lastname2 = o2.getLastName();  

	        Boolean sex1 = o1.getSex();
	        Boolean sex2 = o2.getSex();  

	        Integer age1 = o1.getAge();
	        Integer age2 = o2.getAge();  

	        int compareFirstName = compare(firstname1, firstname2);
	        int compareLastName = compare(lastname1, lastname2);
	        int compareSex = compare(sex1, sex2);

	        if (compareFirstName != 0) {
	            return compareFirstName;
	        }

	        if (compareLastName != 0) {
	            return compareLastName;
	        }

	        if (compareSex != 0) {
	            return compareSex;
	        }

	        return compare(age1, age2);  

	 }
/*public boolean equals(Object obj){
	return true;
}*/
	public static void main(String[] args) {
		  Person[] person = new Person[] {
			         new Person("zhangsan", "gg", Boolean.TRUE, new Integer(27)),
			         new Person("lisi", "mm", Boolean.TRUE, new Integer(27)),
			         new Person("wangwu", "mm", Boolean.FALSE, new Integer(27)),
			         new Person("wangwu", "mm", Boolean.FALSE, new Integer(10))
			     };
			     for (int i = 0; i < person.length; i++) {
			    	 if(i==0)
			    		 System.out.println("排序前:");
			       System.out.println("before sort=" + person[i]);
			     }
			     java.util.Arrays.sort(person, new CompareObject());
			     for (int i = 0; i < person.length; i++) {
			    	 if(i==0)
			    		 System.out.println("排序后:");
			        System.out.println("after sort=" + person[i]);
			     }
	}
}

运行结果:

排序前:

before sort=zhangsan gg 男 27

before sort=lisi mm 男 27

before sort=wangwu mm 女 27

before sort=wangwu mm 女 10

排序后:

after sort=lisi mm 男 27

after sort=wangwu mm 女 10

after sort=wangwu mm 女 27

after sort=zhangsan gg 男 27

注:在实现Comparator接口时,并没有实现equals方法,可程序并没有报错,原因是实现该接口的类也是Object类的子类,而Object类已经实现了equals方法

java Comparator 实现不一样的排序

时间: 2024-10-10 05:45:12

java Comparator 实现不一样的排序的相关文章

[Java] HashMap、TreeMap、Hashtable排序

Java中对Map(HashMap,TreeMap,Hashtable等)的排序时间 首先简单说一下他们之间的区别: HashMap: 最常用的Map,它根据键的HashCode 值存储数据,根据键可以直接获取它的值,具有很快的访问速度.HashMap最多只允许一条记录的键为Null(多条会覆盖);允许多条记录的值为 Null.非 首先简单说一下他们之间的区别: HashMap: 最常用的Map,它根据键的HashCode 值存储数据,根据键可以直接获取它的值,具有很快的访问速度.HashMap

comparator的简单学习(集合排序)

package com.hanchao.test; /**  * 实体类Step  * @author liweihan ([email protected])  * @version 1.0 (2016年1月13日 下午4:30:59)  */ public class Step { /** 处理时间 */ private String acceptTime; /** 快件所在地点*/ private String acceptAddress; public Step() { super();

饿了么开源项目:Java Comparator生成器

版权所有.所有权利保留. 欢迎转载,转载时请注明出处: http://blog.csdn.net/xiaofei_it/article/details/51399159 公司Android项目里经常需要对元素进行排序,而排序都是多字段的,相应的Comparator比较难写.于是我就写了这么一个工具类,用户只需要指定排序规则,便可以自动生成相应的Comparator. 项目地址: https://github.com/Xiaofei-it/ComparatorGenerator 特色 Java编程

Java SortedSet为什么可以实现自动排序?

Set中的SortedSet(SortedSet为TreeSet的实现接口),它们之间的继承关系如下: java.util.Set; java.util.SortedSet; java.util.TreeSet; SortedSet中的元素无序不可重复,但是存进去的元素可以按照元素大小顺序自动排序.结合以下代码来看: import java.util.*;import java.text.*;public class SortedSetTest01{ public static void mai

【Java必修课】一图说尽排序,一文细说Sorting(Array、List、Stream的排序)

# 简说排序 排序是极其常见的使用场景,因为在生活中就有很多这样的实例.国家GDP排名.奥运奖牌排名.明星粉丝排名等,各大排行榜,给人的既是动力,也是压力. 而讲到排序,就会有各种排序算法和相关实现,本文不讲任何排序算法,而只专注于讲使用.通过实例给大家展示,我们可以了解怎样使用既有的工具进行排序.Linux之父说: > Talk is cheap. show me the code! 本文JDK版本为Java 8,但并不代表所介绍到的所有方法只能在JDK1.8上跑,部分方法在之前的版本就已经给

Java几种常用的实现排序方法

import java.util.Random; public class NumberSort{ /** * 私有构造方法,禁止实例化 */ private NumberSort(){ super(); } /** * 冒泡排序 * 比较相邻的元素.如果第一个比第二个大,就叫唤他们两个位置. * 对每一组相邻的元素作同样的工作,从开始的第一对到结束后的最后一对,这样剩下的最后一个应该是最大的数. * 针对所有元素重复以上操作,除了最后一个. * 持续对越来越少的数进行以上的操作,直到没有任何一

Java Comparator

1 Arrays.sort(points, new comparator()); 2 3 public static class comparator implements Comparator<Point> { 4 public int compare(Point p1, Point p2) { 5 return p1.x - p2.x; 6 } Java Comparator,布布扣,bubuko.com

java结构与算法之选择排序

一 .java结构与算法之选择排序 什么事选择排序:从一组无序数据中选择出中小的的值,将该值与无序区的最左边的的值进行交换. 简单的解释:假设有这样一组数据 12,4,23,5,找到最小值 4 放在最右边,然后找到 5 放在  4 的后面,重复该操作. 选择排序参考代码: public class ChooseSort { int[] array = null; @Test public void testPopSort() { array = new int[5]; array[0] = 45

java中数组的三种排序算法

Java中的数组主要有三种排序算法,分别是冒泡排序算法.选择排序算法和插入排序算法. 冒泡排序算法 从数组中首元素开始和其他元素逐个比较,若其中一个元素比其小(或大),就交换首元素与其位置. 选择排序算法 插入排序算法 "我想你只是输在心软,不够卑鄙." 原文地址:https://www.cnblogs.com/yanggb/p/12105421.html