Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

main

[백준-10814번] 나이순 정렬 본문

Algorithm

[백준-10814번] 나이순 정렬

1984 2022. 11. 15. 01:03

* 나이를 비교하기 위해 Comparator를 사용했다.

import java.io.*;
import java.util.*;

public class Main {

	public static void main(String[] args) throws IOException {
		Scanner scan = new Scanner(System.in);
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

		int N = scan.nextInt();
		ArrayList<User> arr = new ArrayList<User>();
		for (int i = 0; i < N; i++) {
			int age = scan.nextInt();
			String name = scan.next();
			arr.add(new User(age, name));
		}
		Collections.sort(arr, new UserAgeComparator());

		for (User user : arr) {
			bw.write(user.age + " " + user.name + "\n");
		}

		bw.flush();
		scan.close();

	}

	static class User {
		int age;
		String name;

		User(int age, String name) {
			this.age = age;
			this.name = name;
		}

		@Override
		public String toString() {
			return this.age + " " + this.name + "\n";
		}

	}

	static class UserAgeComparator implements Comparator<User> {
		@Override
		public int compare(User u1, User u2) {
			if (u1.age > u2.age) {
				return 1;
			} else if (u1.age < u2.age) {
				return -1;
			}
			return 0;
		}
	}

}
728x90
Comments