티스토리 뷰

java에서는 Collections.sort(),Arrays.sort()를 통한 sort함수를 제공하여 정렬을 편리하게 할 수 있다.

기본적으로는 오름차순으로 정렬(String의 경우 사전순)이 되는데 내가 원하는대로 정렬할 수도 있도록 제공한다. 그 방법이 두가지가 있는데, 바로 Comparable 과 Comparator이다

 

 

※Array를 정렬할때는 Array.sort()에서 구현하여 사용가능하고 예제처럼 List를 정렬하고자할때는 Collection.sort()를 사용한다.

 

 

 

-Comparable 

:클래스의 기본 정렬 기준을 설정하는 인터페이스

 

 Comparable 인터페이스를 implements 한 뒤, 내부에 있는 compareTo 메서드원하는 정렬 기준대로 구현하여 사용할 수 있다.

 

-Comparator

:기본 정렬 기준과는 다르게 정렬하고 싶을 때 이용하는 클래스

 

Comparator 클래스를 생성하여,내부에 compare메서드원하는 정렬 기준대로 구현하여 사용할 수 있다.

 

 

 

 

 

당연히 이렇게 정의로만 보면 사용법을 모른다. 코드로 살펴보자!

 

예)학생들을 저장하는 Student 클래스에서 학생들을 학번 오름차순으로 정렬하고자 한다.

 

List<Student> list = new ArrayList<>();

Collections.sort(list); 코드를 통해 간단정렬해보고자 한다.

→여기서는 Comparable을 사용해보자!

 

 

 

-Student.class

//Comparable인터페이스를 implements하여 사용한다
public class Student implements Comparable<Student>{
	
	private int no; 
	private String name;

	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Student(int no, String name) {
		super();
		this.no = no;
		this.name = name;
	}
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * 정렬하는 함수
	 * 양수 : 자리바꿈 일어남.
	 * 0 : 
	 * 음수 : 
	 */
	@Override
	public int compareTo(Student another) {
		return this.no - another.no;
	}
	
    //객체를 print해 확인하기위한 오버라이드
	@Override
	public String toString() {
		return "Student [no=" + no + ", name=" + name + "]";
	}
	
	
	
	
}

 위의 코드에서 compareTo() 메서드를 사용한것을 볼 수 있다. 양수가 나오면, 즉 no가 더 클경우 자리바꿈이 일어나게 된다. 나는 이 음수,양수에대해 굉장히 많이 헷갈렸다. 

오름차순 -> this - another

내림차순 -> another - this

 

사실 compareTo 함수의 return값을 이렇게도 표현할 수 있다.

return Integer.compare(this.no,another.no); ->오름차순 Integer의 포맷을 이용한것이다

 

 

 

compare메소드의 정의를 타고 들어가보면 다음과 같다. 위 Student클래스에서 구현한 compareTo함수에서는 여기의 return부분을 직접 구현해 준것이라고 볼 수 있다.

public static int compare(int x, int y){
    return (x<y)? -1:((x==y)?0:1);
}

 

 

 

 

 

 

 

만약 이런 경우라면 어떻게 해야할까?

예)학생들을 저장하는 Student 클래스에서 학생들을 학번 오름차순으로 정렬하고자 한다. 만약 학번이 같을경우 이름순서대로 정렬한다.

 

위에서 이미 학번 오름차순으로 정렬하는 compareTo메소드를 오버라이딩하여 구현하였다. 그렇다면 이름 순서대로는 이 기본 정렬 기준과 다른 새로운 기준을 세워야한다!! 여기서 사용되는것이 Comparator클래스이다.

 

 

 

대부분 사용은 이렇게 익명 클래스로 많이 사용한다.

Collections.sort(list, new Comparator<Student>(){ 
	@Override 
	public int compare(Student s1, Student s2) { 
		String s1Name = s1.getName(); 
		String s2Name = s2.getName(); 
		Integer s1No = s1.getNo();
		Integer s2No = s2.getNo();
		if(s1No==s2No)
			return s1Name.compareTo(s2Name);
		else
			return Integer.compare(s1No,s2No);
		
	} 
});

 

물론 여기에서 Integer.compare(s1No,s2No) = s1No-s2No 이 가능하다! 더 편한걸로 사용하면 될 듯하다!

 

 

 

 

main문에서 사용한 코드와 실행결과는 이렇게 된다.

public class SortingTest {

	public static void main(String[] args) {
		List<Student> list = new ArrayList<>();
		list.add(new Student(10, "가"));
		list.add(new Student(10, "나"));
		list.add(new Student(17, "라"));
		list.add(new Student(17, "다"));
		list.add(new Student(16, "바"));
        
        //기본정렬 : no 오름차순
		Collections.sort(list);
		System.out.println(list);
        
        //학번이 같을경우 이름순
		Collections.sort(list, new Comparator<Student>(){ 
			@Override 
			public int compare(Student s1, Student s2) { 
				String s1Name = s1.getName(); 
				String s2Name = s2.getName(); 
		        Integer s1No = s1.getNo();
		        Integer s2No = s2.getNo();
		        if(s1No==s2No)
		        	return s1Name.compareTo(s2Name);
		        else
		        	return Integer.compare(s1No,s2No);
			} 
		});
		System.out.println(list);
		

		
	}
}
		

 

정렬된 결과

결과를 보면 학변이 같을경우 이름순의 정렬기준이 있는 2번째줄의 결과창에서는 student 라와 다의 순서가 바뀌어 있는것을 알 수 있다. 

 

 

 

※오름차순 <->내림차순

반대로하려면 인자의 위치를 둘이 바꿔주면 된다!

Collections.sort(list,Collections.reverseOrder()); 로도 같은효과를 볼수 있다.

 

 

 

 

 

 

 

 

 

 

 


 

참고자료

https://m.blog.naver.com/PostView.nhn?blogId=occidere&logNo=220918234464&proxyReferer=https:%2F%2Fwww.google.co.kr%2F

 

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함