키보드워리어

[자바] Collection 활용 - 2 본문

JAVA/입문

[자바] Collection 활용 - 2

꽉 쥔 주먹속에 안경닦이 2023. 4. 10. 12:48
728x90

안녕하세요 오랜만에 돌아온 자바 입문 section 시리즈 15번째 Collection입니다.

 

 

Comparable 인터페이스 구현

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Comparable.html

 

Comparable (Java SE 17 & JDK 17)

Type Parameters: T - the type of objects that this object may be compared to All Known Subinterfaces: ArrayType, ByteValue, CharValue, ChronoLocalDate, ChronoLocalDateTime , Chronology, ChronoZonedDateTime , ClassType, Delayed, DoubleValue, Field, FloatVal

docs.oracle.com

먼저 Comparable 인터페이스를 구현하는 방법부터 알아보겠습니다.

Comparable 인터페이스를 구현하면 해당 클래스의 인스턴스를 정렬할 수 있습니다.

아래는 Comparable 인터페이스를 구현한 Student 클래스 예시입니다.

compareTo 메서드를 오버라이드하여 id값을 기준으로 정렬하도록 구현하였습니다.

public class Student implements Comparable<Student> {

// id, name 입력
    private long id;
    private String name;

// 생성자
    public Student(long id, String name) {
        this.id = id;
        this.name = name;
    }

//getter
    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

@Override
public int compareTo(Student o) {
    if (this.id > o.id) { // 현재 객체의 id가 매개변수로 전달받은 객체의 id보다 큰 경우
        return 1; // 1을 반환하여 오름차순으로 정렬됨
    } else if (this.id < o.id) { // 현재 객체의 id가 매개변수로 전달받은 객체의 id보다 작은 경우
        return -1; // -1을 반환하여 내림차순으로 정렬됨
    } else { // id가 같은 경우
        return 0; // 0을 반환하여 정렬 순서를 바꾸지 않음
    }
}
}

Student 클래스의 id 값을 기준으로 정렬하는데, 현재 객체의 id가 매개변수로 전달받은 객체의 id보다 크면 1을 반환하여 오름차순으로 정렬되도록 하였고, 작으면 -1을 반환하여 내림차순으로 정렬되도록 하였습니다.

 

id가 같은 경우에는 0을 반환하여 정렬 순서를 바꾸지 않도록 하였습니다.

 

 

 

다음으로는 정렬을 위해 Collections 클래스의 sort 메서드를 사용하는 방법을 알아보겠습니다. sort 메서드는 List 타입의 컬렉션을 정렬할 수 있습니다.

아래는 Student 객체를 담은 ArrayList를 생성하고, Collections.sort 메서드를 사용하여 오름차순으로 정렬하는 예시입니다.

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

public class Main {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student(3, "Kim"));
        students.add(new Student(2, "Lee"));
        students.add(new Student(1, "Park"));

        // 오름차순으로 정렬
        Collections.sort(students);

        for (Student student : students) {
            System.out.println(student.getId() + " " + student.getName());
        }
    }
}
//1 Park
//2 Lee
//3 Kim

이제 사용자가 구현한 내림차순으로 정렬하는 방법을 알아보겠습니다. 이를 위해서는 Comparator 인터페이스를 구현해야 합니다. Comparator 인터페이스를 구현한 객체를 Collections.sort 메서드의 두 번째 매개변수로 전달하면 해당 객체에 구현된 정렬 기준에 따라 리스트가 정렬됩니다.

아래는 Comparator 인터페이스를 구현하여 id 값을 기준으로 내림차순으로 정렬하는 예시입니다.

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

public class Main {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student(3, "Kim"));
        students.add(new Student(2, "Lee"));
        students.add(new Student(1, "Park"));

        // 내림차순으로 정렬
        Comparator<Student> descendingOrder = new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return Long.compare(o2.getId(), o1.getId());
            }
        };
        Collections.sort(students, descendingOrder);

        // 결과 출력
        for (Student student : students) {
            System.out.println(student.getId() + " " + student.getName());
        }
    }
}
//3 Kim
//2 Lee
//1 Park

위 코드에서는 Comparator를 익명 클래스로 정의하였습니다. compare 메서드를 오버라이드하여 내림차순으로 비교하는 로직을 구현합니다. 이후 Collections.sort 메서드를 사용하여 List를 정렬합니다.

 

나중에 배울 Stream형을 보면 이것보다 훨씬 간단하게 코드 해볼 수 있습니다.

 

참고하시면 좋은 글

 

2023.03.16 - [JAVA입문/JAVA section 15 - Collections] - [자바] 컬렉션 소개: Java의 List 이해

 
 

https://keyboardwarrior.tistory.com/entry/%EC%9E%90%EB%B0%94Set-%EC%9E%90%EB%A3%8C%EA%B5%AC%EC%A1%B0-%EC%82%B4%ED%8E%B4%EB%B3%B4%EA%B8%B0

 

728x90