• Comparable, Comparator 사용하기 JAVA

    2021. 10. 30.

    by. 순일

     

    Comparable

    Comparable 인터페이스를 상속받은 Node 클래스에서 compareTo 메서드를 재정의하여 정렬한다.

     

    import java.util.ArrayList;
    import java.util.Collections;
    
    public class ComparableTest {
    
    	public static void main(String[] args) {
    		ArrayList<Node> list = new ArrayList<>();
    		list.add(new Node(3 , 5));
    		list.add(new Node(1 , 7));
    		list.add(new Node(2 , 3));
    		Collections.sort(list);
    		System.out.println(list);
    	}
    }
    
    class Node implements Comparable<Node>{ // Comparable implements
    	int x, y;
    	Node(){}
    	Node(int x, int y) {
    		this.x = x;
    		this.y = y;
    	}
    
    	@Override
    	public String toString() {
    		// TODO Auto-generated method stub
    		return "(" + x + "," + y+")";
    	}
    
    	@Override
    	public int compareTo(Node o) {
    		// TODO Auto-generated method stub
    		return this.y - o.y;
    	}
    }

     

    Comparator

    익명 클래스 Comparator를 사용하여 compare 메서드를 재정의하여 정렬한다.

    람다식을 이용해 간단하게 정렬한다.

     

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    
    public class ComparatorTest {
    	public static void main(String[] args) {
    		ArrayList<Node2> list = new ArrayList<>();
    		list.add(new Node2(3, 5));
    		list.add(new Node2(1, 7));
    		list.add(new Node2(2, 3));
    		Collections.sort(list, new Comparator<Node2>() { // 익명 클래스
    			@Override
    			public int compare(Node2 o1, Node2 o2) {
    				// TODO Auto-generated method stub
    				return o1.x - o2.x;
    			}
    		});
    		System.out.println(list);
    		Collections.sort(list, (a, b) -> a.y - b.y); // 람다
    		System.out.println(list);
    	}
    }
    
    class Node2 {
    	int x, y;
    
    	Node2(int x, int y) {
    		this.x = x;
    		this.y = y;
    	}
    
    	@Override
    	public String toString() {
    		// TODO Auto-generated method stub
    		return "(" + x + "," + y + ")";
    	}
    }
    728x90

    댓글