sort()를 사용하기 위해 필요한 것들은:
-->git; java.util.Comparator, java.util.Collections
알고리즘 공부하면서.. 배열만 보면 '닥치고 소팅!' 하고싶은 순간이 여러번 오게 된다.
그 때마다 검색해서 Compare
어쩌구.. Descending / ascending 등 매 번 잘 몰라 고민할 때가 많아 정리해 보려고 한다.
한 줄 요약하자면, Comparable을 implements 한 객체를 compare()해서 sort() 하는 것이다.
세부 내용은 다음과 같다.
sort()를 쓰기 위해서는 다음이 필요하다.
- Arrays, Collections의 object들을 sort() 하여 정렬하려면 자연정렬 하거나.. Comparator를 인자로 주어야 한다.
- 자연정렬은 Arrays.sort(int[] array)로간단하게되지만, (물론 2차 배열은 Comparator 필요)
- List를 정렬하는 Collections.sort()와 같은 것은 Comparator를 인자로 주어야 한다. 어떻게 주느냐..
- Comparator instance를 생성해보면 알겠지만 public int compare()를 override 하게 된다. 여기에 Compare 방법을 구현하면 됨. 음수는 작다 0이면 같다 양수면 크다이다. 쉽지?
- Comparable를 상속한 Object는 compareTo()를 override하면 된다. 아래 예시에 잘 나와 있음. javadoc에는 다음과 같이 되어 있다.
* Sorts the specified list into ascending order, according to the
* {@linkplain Comparable natural ordering} of its elements.
* All elements in the list must implement the {@link Comparable}
* interface. Furthermore, all elements in the list must be
*
mutually comparable (that is, {@code e1.compareTo(e2)}
* must not throw a {@code ClassCastException} for any elements
* {@code e1} and {@code e2} in the list).
- 즉, Comparable을 implement 한 객체만 비교 가능하고 compare()를 override 하여야 한다는 말. 이게 핵심이다. 쉽지? ㅋㅋ
인터넷에서 검색한 예제를 하나 살펴보자.
(출처:http://java67.blogspot.kr/2012/10/how-to-sort-object-in-java-comparator-comparable-example.html)
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
*
* Java program to test Object sorting in Java. This Java program
* test Comparable and Comparator implementation provided by Order
* class by sorting list of Order object in ascending and descending order.
* Both in natural order using Comparable and custom Order using Comparator in Java
*
* @author http://java67.blogspot.com
*/
public class ObjectSortingExample {
public static void main(String args[]) {
//Creating Order object to demonstrate Sorting of Object in Java
Order ord1 = new Order(101,2000, "Sony");
Order ord2 = new Order(102,4000, "Hitachi");
Order ord3 = new Order(103,6000, "Philips");
//putting Objects into Collection to sort
List orders = new ArrayList();
orders.add(ord3);
orders.add(ord1);
orders.add(ord2);
//printing unsorted collection
System.out.println("Unsorted Collection : " + orders);
//Sorting Order Object on natural order - ascending
Collections.sort(orders); //sorting here.
//printing sorted collection
System.out.println("List of Order object sorted in natural order : " + orders);
// Sorting object in descending order in Java
Collections.sort(orders, Collections.reverseOrder());
System.out.println("List of object sorted in descending order : " + orders);
//Sorting object using Comparator in Java
Collections.sort(orders, new Order.OrderByAmount());
System.out.println("List of Order object sorted using Comparator - amount : " + orders);
// Comparator sorting Example - Sorting based on customer
Collections.sort(orders, new Order.OrderByCustomer());
System.out.println("Collection of Orders sorted using Comparator - by customer : " + orders);
}
}
/*
* Order class is a domain object which implements
* Comparable interface to provide sorting on natural order.
* Order also provides copule of custom Comparators to
* sort object based uopn amount and customer
*/
class Order implements Comparable {
private int orderId;
private int amount;
private String customer;
/*
* Comparator implementation to Sort Order object based on Amount
*/
public static class OrderByAmount implements Comparator {
@Override
public int compare(Order o1, Order o2) {
return o1.amount > o2.amount ? 1 : (o1.amount < o2.amount ? -1 : 0);
}
}
/*
* Anohter implementation or Comparator interface to sort list of Order object
* based upon customer name.
*/
public static class OrderByCustomer implements Comparator {
@Override
public int compare(Order o1, Order o2) {
return o1.customer.compareTo(o2.customer);
}
}
public Order(int orderId, int amount, String customer) {
this.orderId = orderId;
this.amount = amount;
this.customer = customer;
}
public int getAmount() {return amount; }
public void setAmount(int amount) {this.amount = amount;}
public String getCustomer() {return customer;}
public void setCustomer(String customer) {this.customer = customer;}
public int getOrderId() {return orderId;}
public void setOrderId(int orderId) {this.orderId = orderId;}
/*
* Sorting on orderId is natural sorting for Order.
*/
@Override
public int compareTo(Order o) {
return this.orderId > o.orderId ? 1 : (this.orderId < o.orderId ? -1 : 0);
}
/*
* implementing toString method to print orderId of Order
*/
@Override
public String toString(){
return String.valueOf(orderId);
}
}
Output
Unsorted Collection : [103, 101, 102]
List of Order object sorted in natural order : [101, 102, 103]
List of object sorted in descending order : [103, 102, 101]
List of Order object sorted using Comparator - amount : [101, 102, 103]
Collection of Orders sorted using Comparator - by customer : [102, 103, 101]
위에서 Order를 sorting 하는방법을 보면
- Order가 Comparable을 implements 하여 compareTo()를 override 했기 때문에 Collections.sort()로 sorting 하는 방법
- Order의 내부에 Comparator를 상속받은 class(OrderByAmount와 OrderByCustomer)를 구현해서 sorting 하는 방법을 구현하고 있다. 잘 안보이나? 코드를 잘 뜯어보면 보인다.
사용하는 관점에서 한번 더 정리를 하자면,
- List를 sorting 하려면 Collections의 sort()를 쓰고 Comparator를 넘겨줘야 하고
- 배열을 sorting 하려면 Arrays의 sort()를 쓰면 된다. 2차 배열은 마찬가지로 Comparator를 넘겨줘야 한다.
- 비교를 하려면 비교 대상(Object)이 Comparable이어야 한다.