java运用Comparator为对象排序

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

排序类:

package com.qimh.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Person{
	
	private String name;
	private int age ;
	private int sex;
	
	public Person(){
		
	}
	
	public Person(String name, int age, int sex) {
		this.name = name;
		this.age = age;
		this.sex = sex;
	}
	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 getSex() {
		return sex;
	}
	public void setSex(int sex) {
		this.sex = sex;
	}
	
	
	
	public static void main(String[] args) {
		List persons = new ArrayList();
		
		persons.add(new Person("cc", 24, 1));
		persons.add(new Person("dd", 45, 0));
		persons.add(new Person("ee", 30, 1));
		persons.add(new Person("ff", 21, 0));
		persons.add(new Person("aa", 20, 0));
		persons.add(new Person("bb", 21, 1));
		
		for (int i = 0; i < persons.size(); i++) {
			Person person = persons.get(i);
			System.out.println(person.getName()+"-"+person.getAge()+"-"+person.getSex());
		}
		
		
		System.out.println("-------------------asc 排序之后-----------------------------");
		
		 Collections.sort(persons, new PersonComparator());
		 for (Person person : persons) {  
			 System.out.println(person.getName()+"-"+person.getAge()+"-"+person.getSex());  
	     }  
		
	}

}

实现Comparator 接口:

package com.qimh.test;

import java.util.Comparator;

public class PersonComparator implements Comparator {


	@Override
	public int compare(Person o1, Person o2) {
		// TODO Auto-generated method stub
		return o1.getName().compareTo(o2.getName());
	}

}

 

测试结果:

cc-24-1
dd-45-0
ee-30-1
ff-21-0
aa-20-0
bb-21-1
-------------------asc 排序之后-----------------------------
aa-20-0
bb-21-1
cc-24-1
dd-45-0
ee-30-1
ff-21-0

 

转载于:https://my.oschina.net/qimhkaiyuan/blog/920176

你可能感兴趣的:(java运用Comparator为对象排序)