public class ExComparator {
	public static void main(String[] args) {
		Pair[] arr = new Pair[10];
		List<Pair> list = new ArrayList<Pair>();
		
		for(int i=0; i<10; i++) {
			int a = (int)(Math.random()*10);
			int b = (int)(Math.random()*10);
			arr[i] = new Pair(a, a+b);
			list.add(arr[i]);
		}
		
		// 정석 Comparator 객체사용 (With array)
		// 오른쪽객체가 왼쪽으로올경우 오름차순
		// 반대는 내림차순
		Arrays.sort(arr, new Comparator<Pair>() {
			@Override
			public int compare(Pair o1, Pair o2) {
				return o2.min - o1.min;
			}
		});
		
		System.out.println("원본");
		System.out.println(list.toString());
		System.out.println();
		
		//2가지 항목비교
		Collections.sort(list, new Comparator<Pair>() {
			public int compare(Pair o1, Pair o2) {
				int first = o2.min - o1.min;
				int second = o2.max - o1.max;
				return first != 0? first : second;
			}
		});
		System.out.println("2개항목비교");
		System.out.println(list.toString());
		System.out.println();
		
		//람다사용 With list (Collections)
		Collections.sort(list, (o1, o2) -> o1.min - o2.min);
		System.out.println("람다로 한개만비교");
		System.out.println(list.toString());
		System.out.println();
		
		
		//Stream 사용
		List<?> sorted = list.stream()
			.sorted((o1,o2) -> o2.min - o1.min)
			.collect(Collectors.toList());
		System.out.println("Stream 사용");
		System.out.println(sorted.toString());
		System.out.println();
		
	}
}

class Pair {
	int min;
	int max;
	
	Pair(int min, int max) {
		this.min = min;
		this.max = max;
	}
	
	@Override
	public String toString() {
		return String.format("[%d, %d]", min,max);
	}
}

+ Recent posts