Comparator 대상 집합 을 바탕 으로 여러 조건 을 우선 순위 에 따라 비교 합 니 다.

배경
일상적인 자바 개발 에서 우 리 는 한 대상 의 집합 을 되 돌려 줄 때 대상 의 특정한 속성 이나 특정한 속성 에 따라 정렬 하여 전단 에 보 여 줘 야 한다.예 를 들 어 나 는 최근 에 문제 라 이브 러 리 집합 을 되 돌려 야 한다.먼저 지 정 된 시간 에 따라 정렬 한 다음 에 건설 시간 에 따라 정렬 해 야 한다.my sql 층 에서 조작 하 는 것 이 비교적 번 거 롭 고 시간 을 낭비 해 야 한다.우 리 는 프로그램 을 통 해 정렬 할 수 있다.
사례 코드

//    
public class People {
	private Integer id;
	private String name;
	private Integer topTime;//     
	private Integer gmtCreate;//      
	public People(Integer id, String name, Integer topTime, Integer gmtCreate) {
		super();
		this.id = id;
		this.name = name;
		this.topTime = topTime;
		this.gmtCreate = gmtCreate;
	}
 
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getTopTime() {
		return topTime;
	}
	public void setTopTime(Integer topTime) {
		this.topTime = topTime;
	}
	public Integer getGmtCreate() {
		return gmtCreate;
	}
	public void setGmtCreate(Integer gmtCreate) {
		this.gmtCreate = gmtCreate;
	}
 
	@Override
	public String toString() {
		return "People [id=" + id + ", name=" + name + ", topTime=" + topTime + ", gmtCreate=" + gmtCreate + "]";
	}
}

//     
public class PeopleComparator implements Comparator<People>{
 
	@Override
	public int compare(People o1, People o2) {
		int result = 0;
		//           (o1,o2        )
		int topTimeSeq = o2.getTopTime() - o1.getTopTime();
		if(topTimeSeq != 0){
			result = (topTimeSeq > 0) ? 3 : -1;
		}else{
			//         
			topTimeSeq = o2.getGmtCreate() - o1.getGmtCreate();
			if(topTimeSeq != 0){
				result = (topTimeSeq > 0) ? 2 : -2;
			}
		}
		return result;
	}
}

//   
public class PeopleTest {
	public static void main(String[] args) {
		List<People> peopleList = new ArrayList<People>(){
			{
				add(new People(1,"tom1",0,1));
				add(new People(2,"tom2",2,4));
				add(new People(3,"tom3",1,3));
				add(new People(4,"tom4",0,6));
				add(new People(5,"tom5",0,2));
				add(new People(6,"tom6",0,5));
			}
		};
		Collections.sort(peopleList,new PeopleComparator());
		for(People p:peopleList){
			System.out.println(p.toString());
		}
	}
}
테스트 결과

Comparator 다 중 조건 비교

class Card {
    int a;
    int b;
    public Card(int a, int b) {
        this.a = a;
        this.b = b;
    }
    public int getA() {
        return a;
    }
    public int getB() {
        return b;
    }
    @Override
    public String toString() {
        return "Card{" +
                "a=" + a +
                ", b=" + b +
                '}';
    }
}
public class Main {
    public static void main(String[] args) {
        List<Card> list = new ArrayList<>();
        list.add(new Card(0, 2));
        list.add(new Card(1, 1));
        list.add(new Card(1, 0));
        list.add(new Card(1, 0));
        list.add(new Card(2, 0));
        System.out.println(list);
        System.out.println();
        
        Collections.sort(list, new Comparator<Card>() {
            @Override
            public int compare(Card c1, Card c2) {
                // c1 - c2    
                // c2 - c1    
                int res1 = c2.b - c1.b;
                int res2 = c2.a - c1.a;
                //   b     a,      b
                return res1 == 0 ? res2 : res1;
            }
        });
        System.out.println(list);
    }
}
[Card{a=0, b=2}, Card{a=1, b=1}, Card{a=1, b=0}, Card{a=1, b=0}, Card{a=2, b=0}]
[Card{a=0, b=2}, Card{a=1, b=1}, Card{a=2, b=0}, Card{a=1, b=0}, Card{a=1, b=0}]
이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기