본문 바로가기

JAVA/JAVA

[JAVA] Colletions Sort - 리스트 정렬하기

 

자바에서 리스트를 정렬할때, 반복문을 써서 직접 리스트 정렬을 구현해도 되지만, 그 이상 혹은 다른 기능이 필요한 것이 아니라면, 제공해주는 기능을 굳이 만들어서 사용할 필요는 없다.

아래의 Collections 클래스에서 제공해주는 메소드들을 이용하여 개발을 해보자.

참조 URL :  https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html

 

Collections (Java Platform SE 7 )

Rotates the elements in the specified list by the specified distance. After calling this method, the element at index i will be the element previously at index (i - distance) mod list.size(), for all values of i between 0 and list.size()-1, inclusive. (Thi

docs.oracle.com

 

예제 1. 기본 리스트 (역)정렬 

import java.util.*; 

public class CollectionsExample 
{ 
	public static void main(String[] args) 
	{ 
    ArrayList<String> list = new ArrayList<String>();
    list.add("B");
    list.add("A");
    list.add("D");
    list.add("C");
    list.add("F");

    // 기본 정렬
    Collections.sort(list);
    System.out.println("LIST : " + list);

    // 역순 정렬
    Collections.sort(list, Collections.reverseOrder());
    System.out.println("LIST : " + list);

    ArrayList<Integer> list2 = new ArrayList<Integer>();
    list2.add(3);
    list2.add(2);
    list2.add(1);
    list2.add(5);
    list2.add(4);

    // 기본 정렬
    Collections.sort(list2);
    System.out.println("LIST : " + list2);

    // 역순 정렬
    Collections.sort(list2, Collections.reverseOrder());
    System.out.println("LIST : " + list2);
        
	} 
}

// RESULT *******
// LIST : [A, B, C, D, F]
// LIST : [F, D, C, B, A]
// LIST : [1, 2, 3, 4, 5]
// LIST : [5, 4, 3, 2, 1]

 

위와같이 단순히 STRING, INTEGER .. 등과 같은 우선순위가 분명한 경우에는 간단하게 정렬을 해볼 수 있다.

 

예제 2. 클래스 나열 - 키순으로 학생들을 나열해보자. (오름차순, 내림차순) 

class Student {
  int num, height;
  String name;

  // Constructor
  public Student(int num, String name, int height) {
    this.num = num;
    this.name = name;
    this.height = height;
  }

  public int getHeight() {
    return height;
  }

  public int getNum() {
    return num;
  }

  public String getName() {
    return name;
  }

}


public class testClass {
  public static void main(String[] args) {
    ArrayList<Student> students = new ArrayList<Student>();
    students.add(new Student(1, "김아무개", 170));
    students.add(new Student(2, "최아무개", 180));
    students.add(new Student(3, "김아무개", 175));
    students.add(new Student(4, "박아무개", 185));

	// 내림차순
    Collections.sort(students, new Comparator<Student>() {
      @Override
      public int compare(Student o1, Student o2) {
        return o2.getHeight() - o1.getHeight();
      }
    });

    for (Student item : students) {
      System.out.println(item.getNum() + "," + item.getName() + " : " + item.getHeight());
    }
    
	// 오름차순
    Collections.sort(students, new Comparator<Student>() {
      @Override
      public int compare(Student o1, Student o2) {
        return o1.getHeight() - o2.getHeight();
      }
    });

    for (Student item : students) {
      System.out.println(item.getNum() + "," + item.getName() + " : " + item.getHeight());
    }
 }
 
 
 /* 결과
4,박아무개 : 185
2,최아무개 : 180
3,김아무개 : 175
1,김아무개 : 170
--------------------------
1,김아무개 : 170
3,김아무개 : 175
2,최아무개 : 180
4,박아무개 : 185
*/