logo

컬렉션에서 정렬

다음 요소를 정렬할 수 있습니다.

  1. 문자열 객체
  2. 래퍼 클래스 객체
  3. 사용자 정의 클래스 객체
컬렉션 클래스는 컬렉션의 요소를 정렬하기 위한 정적 메서드를 제공합니다. 컬렉션 요소가 Set 유형인 경우 TreeSet을 사용할 수 있습니다. 그러나 List의 요소를 정렬할 수는 없습니다. Collections 클래스는 List 유형 요소의 요소를 정렬하는 메소드를 제공합니다.

List 요소를 정렬하기 위한 Collections 클래스의 방법

공개 무효 정렬(목록 목록): List의 요소를 정렬하는 데 사용됩니다. 목록 요소는 Comparable 유형이어야 합니다.

참고: String 클래스와 Wrapper 클래스는 Comparable 인터페이스를 구현합니다. 따라서 문자열이나 래퍼 클래스의 개체를 저장하면 비교 가능합니다.

문자열 객체를 정렬하는 예

 import java.util.*; class TestSort1{ public static void main(String args[]){ ArrayList al=new ArrayList(); al.add('Viru'); al.add('Saurav'); al.add('Mukesh'); al.add('Tahir'); Collections.sort(al); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } 
지금 테스트해보세요
 Mukesh Saurav Tahir Viru 

문자열 객체를 역순으로 정렬하는 예

 import java.util.*; class TestSort2{ public static void main(String args[]){ ArrayList al=new ArrayList(); al.add('Viru'); al.add('Saurav'); al.add('Mukesh'); al.add('Tahir'); Collections.sort(al,Collections.reverseOrder()); Iterator i=al.iterator(); while(i.hasNext()) { System.out.println(i.next()); } } } 
 Viru Tahir Saurav Mukesh 

래퍼 클래스 객체를 정렬하는 예

 import java.util.*; class TestSort3{ public static void main(String args[]){ ArrayList al=new ArrayList(); al.add(Integer.valueOf(201)); al.add(Integer.valueOf(101)); al.add(230);//internally will be converted into objects as Integer.valueOf(230) Collections.sort(al); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } 
 101 201 230 

사용자 정의 클래스 객체를 정렬하는 예

 import java.util.*; class Student implements Comparable { public String name; public Student(String name) { this.name = name; } public int compareTo(Student person) { return name.compareTo(person.name); } } public class TestSort4 { public static void main(String[] args) { ArrayList al=new ArrayList(); al.add(new Student('Viru')); al.add(new Student('Saurav')); al.add(new Student('Mukesh')); al.add(new Student('Tahir')); Collections.sort(al); for (Student s : al) { System.out.println(s.name); } } } 
 Mukesh Saurav Tahir Viru