개발/Java

자바 배열, 리스트 정렬 (Array, List 정렬)

1mj 2021. 11. 2. 15:18

배열(Array) 정렬

오름차순 정렬

int[] arr = {1, 2, 4, 5, 3};
Arrays.sort(arr);

 

내림차순 정렬

int[] arr = {1, 2, 4, 5, 3};
Arrays.sort(arr, Collections.reverseOrder());

 

일부만 정렬

int[] arr = {1, 2, 5, 4, 3};	// 1 2 4 5 3
Arrays.sort(arr, 0, 4);		// 1, 2, 4, 5 요소만 정렬

리스트(List) 정렬

오름차순 정렬

ArrayList<String> list = new ArrayList<>(Arrays.asList("c", "a", "b"));
Collections.sort(list);	// a b c
ArrayList<String> list = new ArrayList<>(Arrays.asList("c", "a", "b"));
list.sort(Comparator.naturalOrder());	// a b c

 

내림차순 정렬

ArrayList<String> list = new ArrayList<>(Arrays.asList("c", "a", "b"));
Collections.sort(list, Collections.reverseOrder());	// c b a
ArrayList<String> list = new ArrayList<>(Arrays.asList("c", "a", "b"));
list.sort(Comparator.reverseOrder());	// a b c

 

객체 정렬(Comparator 사용)

public class Main {
	public static void main(String[] args) {
		List<Student> studentList = new ArrayList<Student>(); // 값 추가 생략
		Comparator<Student> comparator = new Comparator<Student>() {
			@Override
			public int compare(Student a, Student b) {
				return a.getAge() - b.getAge();	// 오름차순
			}
		};
		Collections.sort(studentList, comparator);
	}
}

public class Student {
    private String name;
    private int age;

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