Comparable과 Comparator
TreeSet과 TreeMap의 자동 정렬
TreeSet의 객체와 TreeMap의 키는 저장과 동시에 자동 오름차순 정렬
숫자(Integer, Double)타입일 경우에는 값으로 정렬
문자열(String) 타입일 경우에는 유니코드로 정렬
TreeSet과 TreeMap은 정렬 위해 java.lang.Comparable을
구현 객체를 요구
Integer, Double, String은 모두 Comparable 인터페이스 구현
Comparable을 구현하고 있지 않을 경우에는 저장하는 순간 ClassCastException 발생
package c4_tree.comparable;
import java.util.TreeSet;
//Person타입 비교하려면 Comparable 인터페이스 구현해야함.
class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Person o) {
// 반환하는 값이 0 또는 음수면 제자리
// 양수면 변경
// 나이를 기준으로 오름차순 정렬
return this.age - o.age;
}
}
public class ComparableExample {
public static void main(String[] args) {
TreeSet<Integer> intSet = new TreeSet<>();
intSet.add(50);
intSet.add(70);
intSet.add(60);
System.out.println(intSet);
System.out.println("======================");
TreeSet<Person> set = new TreeSet<>();
set.add(new Person("최기근",26));
set.add(new Person("이진형",17));
set.add(new Person("김진우",56));
set.add(new Person("김선경",29));
System.out.println(set);
}
}
package c4_tree.comparator;
import java.util.Comparator;
//Comparator:외부에서 정렬기준 결정해줌
public class DecendingComparator implements Comparator<Fruit>{
@Override
public int compare(Fruit o1, Fruit o2) {
// o1 == 새로 추가된 값
// o2 == 기존 값
// 새로운 값 - 기존값 == 양수면 자리 교체
// compareTo != compare
System.out.println("compare : " + o2 + "-" + o1);
return o2.getPrice() - o1.getPrice(); // 내림차순
}
}
package c4_tree.comparator;
import java.util.Comparator;
import java.util.TreeSet;
public class ComparatorExample {
public static void main(String[] args) {
//정렬기준 추가 1번째 방법.(재활용시 클래스 따로 만듬)
Comparator<Fruit> compare = new DecendingComparator();
TreeSet<Fruit> set = new TreeSet<>(compare); //생성자에 넣어줌.
set.add(new Fruit("포도",3000));
set.add(new Fruit("딸기",1500));
set.add(new Fruit("수박",10000));
System.out.println(set);
//2번째 방법. 익명구현객체(implements Comparator 만드는거랑 똑같음)
Comparator<Fruit> compare2 = new Comparator<>() {
String name;
@Override
public int compare(Fruit o1, Fruit o2) {
return o1.getPrice() - o2.getPrice(); // 오름차순
}
};
TreeSet<Fruit> treeSet2 = new TreeSet<>(compare2);
treeSet2.add(new Fruit("포도",3000));
treeSet2.add(new Fruit("딸기",1500));
treeSet2.add(new Fruit("수박",10000));
System.out.println(treeSet2);
//3번째 방법. 변수에 안담고 바로 전달도 가능
TreeSet<Fruit> treeSet3 = new TreeSet<>(new Comparator<>() {
String name;
@Override
public int compare(Fruit o1, Fruit o2) {
return o1.getPrice() - o2.getPrice();
}
});
}
}
package c4_tree.comparator;
public class Fruit {
private String name;
private int price;
// 생성자, getter, toString
public Fruit(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
@Override
public String toString() {
return "Fruit [name=" + name + ", price=" + price + "]";
}
}
package c6_collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for(int i = 1; i <= 45;i++) {
list.add(i);
}
System.out.println(list);
// 섞는다.
Collections.shuffle(list);
System.out.println(list);
System.out.println("===========================");
// list에서 시작인덱스부터 필요한 크기만큼만 잘라서 새로운 리스트 생성
List<Integer> lotto = list.subList(0,6);
System.out.println(lotto);
System.out.println("================================");
System.out.println("정렬 전 : "+lotto);
Collections.sort(lotto);
System.out.println("정렬 후 : "+lotto);
Collections.reverse(lotto);
System.out.println("reverse : "+lotto);
System.out.println("==============================");
System.out.println(Collections.max(lotto));
System.out.println(Collections.min(lotto));
}
}