Java에서의 정렬

Jinjin·2023년 10월 21일
0
post-thumbnail

Comparble과 Comparator

정렬 클래스를 정의한 후 Comparable 클래스의 compareTo 메소드를 오버라이딩해서 정의하고 추가로 정렬하는 경우에는 Comparatorcompare 메소드를 오버라이딩해서 정렬한다.
아니면, 무명클래스를 생성한 후 바로 정렬하는 방법도 가능하다.

package nexon.ct;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
// Comparable - compareTo
// Comparator - compare
// 문자열에서 compareTo는 사전적순서 => s1.compareTo(s2) 할 때 s1이 s2보다 앞선 순서면 음수, 아니면 양수
// 처음 정렬하는 경우에는 Comparable을 쓰고 또 정렬할 때는 Comparator를 보통 쓴다.

class Student{
	int age;
	int weight;
	String name;
	
	public Student(int age, int weight, String name) {
		this.age = age;
		this.weight = weight;
		this.name = name;
	}

	@Override
	public String toString() {
		return "Student [age=" + age + ", weight=" + weight + ", name=" + name + "]";
	}
}

class descendingAge implements Comparator<Student>{
	public int compare(Student s1, Student s2) {
		return Integer.valueOf(s2.age).compareTo(s1.age); // 나이를 순서대로 내림차순 정렬한다.
	}
}
public class Main {
	public static void main(String[] args) {
		List<Student> students = new ArrayList<>();
		Collections.addAll(students, new Student(5, 10, "루루"),new Student(5, 10, "하이루"), new Student(3, 10, "영미"),
				new Student(3, 8, "몜"), new Student(3, 10, "철수"));
		
		Collections.sort(students, new Comparator<Student>() {
			public int compare(Student s1, Student s2) {
				// 나이는 오름차순
				// 몸무게는 내림차순
				// 이름은 사전 순서대로 오름차순
				if(s1.age < s2.age) {
					return Integer.valueOf(s1.age).compareTo(s2.age);
				}else if(s1.age == s2.age) {
					if(s1.weight > s2.weight) {
						return Integer.valueOf(s2.weight).compareTo(s1.weight); // 내림차순
					}else if(s1.weight == s2.weight) {
						return s1.name.compareTo(s2.name); // 이름은 오름차순 
					}
				}
				
				return 0;
			}
		});
		System.out.println(students);
		
		Collections.sort(students, new descendingAge()); // 나이를 기준으로 내림차순
		
		System.out.println(students);
	}
}
profile
BE Developer

0개의 댓글