重写Comparator和Comparable方法,以及Map按value排序

继承Comparator接口,重写compare()方法

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;


class Student implements Comparator{
	String name;
	int age;
	int id;
	public Student(){}
	public Student(String name,int age,int id)
	{
		this.name=name;
		this.age=age;
		this.id=id;
	}
	@Override
	public int compare(Student o1, Student o2) {
		// TODO Auto-generated method stub
		return o1.age-o2.age;
	}
}

public class Test {

	public static void main(String[] args) {
		Random rand=new Random();
		List list=new ArrayList();
		for(int i=0;i<20;i++)
		{
			Student ss=new Student("long-jing-wen-"+i,rand.nextInt(100),rand.nextInt(1000));
			list.add(ss);
			
		}
		
		Student student=new Student();
		Collections.sort(list, student);

		
		
		for(int i=0;i
}}
 
  
继承Comparable,重写compareTo()方法

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;


class Student2 implements Comparable{
	String name;
	int age;
	int id;
	
	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 int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}

	public Student2(){}
	public Student2(String name,int age,int id)
	{
		this.name=name;
		this.age=age;
		this.id=id;
	}

	@Override
	public int compareTo(Student2 o) {
		// TODO Auto-generated method stub
		return this.id-o.id;
	}

}



public class Test {

	public static void main(String[] args) {
		Random rand=new Random();		
		Student2[] stu=new Student2[20];
		
		
		for(int i=0;i<20;i++)
		{
			Student2 ss2=new Student2("long-jing-wen-"+i,rand.nextInt(100),rand.nextInt(1000));
			stu[i]=ss2;
		}
		treemap.putAll(map);
		
		Arrays.sort(stu);
		
		
		for(int i=0;i


Map按value排序

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

public class Testing {

	public static void main(String[] args) {

		HashMap map = new HashMap();
	
		map.put("A", (long) 99);
		map.put("B", (long) 67);
		map.put("C", (long) 109);
		map.put("D", (long) 2);

		System.out.println("unsorted map: " + map);

		List> list = new ArrayList<>(map.entrySet());
		Collections.sort(list, new Comparator>() {
			public int compare(Map.Entry o1,
					Map.Entry o2) {
				return (int) (o2.getValue()-o1.getValue() );
			}
		});

		System.out.println("results: " + list);
		

	}
}



你可能感兴趣的:(算法,文章)