Java中比较器小结

        比较器指的是集合存储的元素的特性,如果元素是可比较的则可以进行相应的排序,否则不行。但是在Java中有Comparable接口和Comparator接口,具体有什么区别呢?

        对于Comparable接口来说,它往往是进行比较类需要实现的接口,它仅包含一个有compareTo()方法,只有一个参数,返回值为int,返回值大于0表示对象大于参数对象;小于0表示对象小于参数对象;等于0表示两者相等

public class TestComparable implements Comparable{

	private String name; //主键
	private int age;     //年龄
	public TestComparable(String name, int age){
		this.name = name;
		this.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(Object obj) {//覆盖Comparable接口的compareTo()接口
		return this.age - ((TestComparable)obj).getAge();
	}
	
	public static void main(String[] args) {
		TestComparable user1 = new TestComparable("user001", 24);
		TestComparable user2 = new TestComparable("user002", 20);
		if(user1.compareTo(user2) > 0)//具体使用就是通过对象调用普通方法一样,返回值是对象值与参数值比较的结果
			System.out.println("用户1年龄较大.");
		else if(user1.compareTo(user2) < 0)
			System.out.println("用户2年龄较大.");
		else System.out.println("两用户年龄一样大.");
	}
}


        对于Comparator接口来说,它的实现者被称为比较器,它包含一个compare()方法,有两个参数,返回值与Comparable的compareTo()方法一样,不同之处是Comparator接口一般不会被集合元素类所实现,而是单独实现或者匿名内部类方式实现

public class TestComparator{

	private String name; //主键
	private int age;     //年龄
	public TestComparator(String name, int age){
		this.name = name;
		this.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;
	}
	
	public static void main(String[] args){
		TestComparator user1 = new TestComparator("user001", 24);
		TestComparator user2 = new TestComparator("user002", 20);
		Comparator cmp = new Comparator(){//以内部类的形式实现Comparator接口
			@Override
			public int compare(Object obj1, Object obj2) {
				TestComparator user1 = (TestComparator)obj1;//类型转换
				TestComparator user2 = (TestComparator)obj2;
				return user1.getAge() - user2.getAge();//两参数对象进行比较
			}			
		};
		int res = cmp.compare(user1, user2);//比较结果是第一个对象与第二个对象的比较值
		if(res > 0)
			System.out.println("用户1年龄较大.");
		else if(res < 0)
			System.out.println("用户2年龄较大.");
		else System.out.println("两用户年龄一样大.");
	}
}

        比较器是把集合或数组的元素强行按照指定方法进行排序的对象,它是实现了Comparator接口类的实例。如果一个集合元素是可比较的(实现了Comparable接口),那么就具有了默认排序方法,比较器则是强行改变它默认的比较方式来进行排序。或者有的集合元素不可比较(没有实现Comparable接口),则可用比较器来实现动态的排序。


        下面举例写一个HashMap分别按照Key排序和按照Value排序的程序:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

//对Map按key排序和按value排序

public class MapSortTest {
	//sort by key.
	public static Map sortMapByKey(Map oriMap){
		if(oriMap==null || oriMap.isEmpty())
			return null;
		MapsortedMap = new TreeMap(new Comparator(){
			@Override
			public int compare(String key1, String key2) {
//				int intKey1 = Integer.valueOf(key1);
//				int intKey2 = Integer.valueOf(key2);
//				return intKey1 - intKey2;
				return key1.compareTo(key2);
			}
			
		});		
		sortedMap.putAll(oriMap);
		return sortedMap;
	}
	
	
	//sort by value
	public static Map sortMapByValue(Map oriMap){
		Map sortedMap = new LinkedHashMap();
		if(oriMap!=null || !oriMap.isEmpty()){
			List> entryList = new ArrayList>(oriMap.entrySet());
			Collections.sort(entryList, new Comparator>(){
				@Override
				public int compare(Entry entry1, Entry entry2) {
//					int value1 = Integer.valueOf(entry1.getValue());
//					int value2 = Integer.valueOf(entry2.getValue());
//					return value1 - value2;
					return entry1.getValue().compareTo(entry2.getValue());
				}				
			});
			Iterator> iter = entryList.iterator();
			Map.Entry tmpEntry = null;
			while(iter.hasNext()){
				tmpEntry = iter.next();
				sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
			}			
		}
		
		return sortedMap;
	}
	
	public static void main(String[] args) {
		Map map = new HashMap<>();
		map.put("zhangsan", "29");
		map.put("lisi", "35");
		map.put("wangwu", "40");
		map.put("mazi",	"24");
		
		System.out.println("The original map: " + map);
		System.out.println("Sort by key: " + sortMapByKey(map));
		System.out.println("Sort by value: " + sortMapByValue(map));
	}

}


你可能感兴趣的:(Java)