๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/Java

์ž๋ฐ” ๋ฐฐ์—ด, ๋ฆฌ์ŠคํŠธ ์ •๋ ฌ (Array, List ์ •๋ ฌ)

by 1mj 2021. 11. 2.

๋ฐฐ์—ด(Array) ์ •๋ ฌ

์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ

int[] arr = {1, 2, 4, 5, 3};
Arrays.sort(arr);

 

๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ

int[] arr = {1, 2, 4, 5, 3};
Arrays.sort(arr, Collections.reverseOrder());

 

์ผ๋ถ€๋งŒ ์ •๋ ฌ

int[] arr = {1, 2, 5, 4, 3};	// 1 2 4 5 3
Arrays.sort(arr, 0, 4);		// 1, 2, 4, 5 ์š”์†Œ๋งŒ ์ •๋ ฌ

๋ฆฌ์ŠคํŠธ(List) ์ •๋ ฌ

์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ

ArrayList<String> list = new ArrayList<>(Arrays.asList("c", "a", "b"));
Collections.sort(list);	// a b c
ArrayList<String> list = new ArrayList<>(Arrays.asList("c", "a", "b"));
list.sort(Comparator.naturalOrder());	// a b c

 

๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ

ArrayList<String> list = new ArrayList<>(Arrays.asList("c", "a", "b"));
Collections.sort(list, Collections.reverseOrder());	// c b a
ArrayList<String> list = new ArrayList<>(Arrays.asList("c", "a", "b"));
list.sort(Comparator.reverseOrder());	// a b c

 

๊ฐ์ฒด ์ •๋ ฌ(Comparator ์‚ฌ์šฉ)

public class Main {
	public static void main(String[] args) {
		List<Student> studentList = new ArrayList<Student>(); // ๊ฐ’ ์ถ”๊ฐ€ ์ƒ๋žต
		Comparator<Student> comparator = new Comparator<Student>() {
			@Override
			public int compare(Student a, Student b) {
				return a.getAge() - b.getAge();	// ์˜ค๋ฆ„์ฐจ์ˆœ
			}
		};
		Collections.sort(studentList, comparator);
	}
}

public class Student {
    private String name;
    private int age;

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

 

๋Œ“๊ธ€