๐Ÿ’ป ๊ณต๋ถ€ ๊ธฐ๋ก/โ˜• Java

Java | Comparator

  • -

๋ฆฌ์ŠคํŠธ๋กœ ๊ฐ€์ ธ์˜จ ๊ฐ’์„ ๊ฐ€์ง€๊ณ  ํŠน์ • ๊ธฐ์ค€์„ ์„ธ์›Œ ์˜ค๋ฆ„์ฐจ์ˆœ, ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์•Œ์•„๋ณด์ž.

 

์ •์˜

  • ์ •๋ ฌ ๊ฐ€๋Šฅํ•œ ํด๋ž˜์Šค(Comparable ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•œ ํด๋ž˜์Šค)๋“ค์˜ ๊ธฐ๋ณธ ์ •๋ ฌ ๊ธฐ์ค€๊ณผ ๋‹ค๋ฅด๊ฒŒ ์ •๋ ฌ ํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ์ธํ„ฐํŽ˜์ด์Šค
  • package: java.util.Comparator
    • ์ฃผ๋กœ ์ต๋ช… ํด๋ž˜์Šค๋กœ ์‚ฌ์šฉ๋œ๋‹ค.
    • ๊ธฐ๋ณธ์ ์ธ ์ •๋ ฌ ๋ฐฉ๋ฒ•์ธ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ์„ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•  ๋•Œ ๋งŽ์ด ์‚ฌ์šฉํ•œ๋‹ค.

 

์˜ˆ์‹œ

List<Student> list = new ArrayList<>();
Student s1 = new Student(11001244, "์•„๋ฌด๊ฐœ", "์„œ์šธ์‹œ ๊ธˆ์ฒœ๊ตฌ");
Student s2 = new Student(25109435, "๊น€๊น€๊น€", "์„œ์šธ์‹œ ์ค‘๋ž‘๊ตฌ");
Student s3 = new Student(11005338, "์‚ฌ์ด๋‹ค", "์„œ์šธ์‹œ ์€ํ‰๊ตฌ");
list.add(s1);
list.add(s2);
list.add(s3);

Collections.sort(list, new StudentCompare());

์œ„ ์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

 

์ด์ œ ์ด ์ƒํƒœ์—์„œ ๊ธฐ์ค€์„ ์ •์˜ํ•ด ์›ํ•˜๋Š” ํ˜•ํƒœ์˜ ์ •๋ ฌ์„ Comparator ๋กœ ํ•ด๋ณด์ž.

//๋ชจ๋‘ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ
list.sort(Comparator.comparing(Student::getNum).thenComparing(Student::getName)
        .thenComparing(Student::getAddress));
 
//์ด๋ฆ„๋งŒ ๋‚ด๋ฆผ์ฐจ์ˆœ         
Comparator<Student> reverse = Comparator.comparing(Student::getName).reversed();
list.sort(Comparator.comparing(Student::getNum).thenComparing(reverse)
        .thenComparing(Student::getAddress));

 

์ธํ„ฐํŽ˜์ด์Šค Comparator ๊ฐ์ฒด์˜ reverse ๋ฅผ ๋งŒ๋“ค์–ด ์ •๋ ฌ ๊ธฐ์ค€์„ ์ •์˜ํ•˜๊ณ , sort ์ •๋ ฌ์—์„œ ๊ฐ์ฒด๋ฅผ ์ž…๋ ฅํ•˜๋ฉด ์ •์˜ํ•œ ๊ธฐ์ค€๋Œ€๋กœ ์ •๋ ฌ๋œ๋‹ค.

 

 

์ถœ์ฒ˜ | https://gmlwjd9405.github.io/2018/09/06/java-comparable-and-comparator.html

์ถœ์ฒ˜ | ๋น ์—์•ผ๋Š” ๊ฐœ๋ฐœ์ค‘

Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.