: 데이터의 집합을 어떠한 기준(핵심항목, key)의 대소관계를 따져 일정한 순서로 줄지어 놓는 것을 의미한다.
import java.util.*;
public class Main {
public static void main(String [] args){
int [] arr = {4,6,2,3,1};
Arrays.sort(arr);
}
}
Integer에서만 가능, int 불가
import java.util.*;
public class Main {
public static void main(String [] args){
Integer [] arr = {4,6,2,3,1};
Arrays.sort(arr, Collections.reverseOrder());
}
}
import java.util.*;
public class Main {
public static void main(String [] args){
String [] str = {"ac","sa","ag"};
List strlist = Arrays.asList(str);
Collections.sort(strlist);
}
}
import java.util.*;
public class Main {
public static void main(String [] args){
String [] str = {"ac","sa","ag"};
List strlist = Arrays.asList(str);
Collections.sort(strlist);
//먼저 오름차순 정렬을 수행한다.
Collections.reverse(strlist);
}
}
import java.util.*;
public class Main {
public static void main(String [] args){
Character [] chr = {'a','z','s'};
Arrays.sort(chr);
for(int i =0; i<chr.length; i++){
System.out.print(chr[i]+" ");
}
}
}
Charater에서만 가능, char 불가
import java.util.*;
public class Main {
public static void main(String [] args){
Character [] chr = {'a','z','s'};
Arrays.sort(chr);
//먼저 오름차순 정렬을 수행한다.
Arrays.sort(chr,Collections.reverseOrder());
for(int i =0; i<chr.length; i++){
System.out.print(chr[i]+" ");
}
}
}
int[][] intrr = new int[][]{{5,40},{3,50},{1,30},{4,20},{2,10}};
Arrays.sort(intrr, Comparator.comparingInt((int[] o) -> o[0])); //첫 번째 숫자 기준 오름차순 정렬
Arrays.sort(intrr, Comparator.comparingInt((int[] o) -> o[1])); //두 번째 숫자 기준 오름차순 정렬
int[][] intrr = new int[][]{{5,40},{3,50},{1,30},{4,20},{2,10}};
Arrays.sort(intrr, Comparator.comparingInt((int[] o) -> o[0]).reversed()); //첫 번째 숫자 기준 내림차순 정렬
Arrays.sort(intrr, Comparator.comparingInt((int[] o) -> o[1]).reversed()); //두 번째 숫자 기준 내림차순 정렬
import java.util.*;
public class Main {
public static void main(String [] args){
Integer [] arr = {4,6,2,3,1};
List list = Arrays.asList(arr);
Collections.sort(list);
}
}
import java.util.*;
public class Main {
public static void main(String [] args){
Integer [] arr = {4,6,2,3,1};
List list = Arrays.asList(arr);
Collections.sort(list);
Collections.reverse(list);
}
}
import java.util.*;
public class Main {
public static void main(String [] args){
String [] str = {"ac","sa","ag"};
List strlist = Arrays.asList(str);
Collections.sort(strlist);
}
}
import java.util.*;
public class Main {
public static void main(String [] args){
String [] str = {"ac","sa","ag"};
List strlist = Arrays.asList(str);
Collections.sort(strlist);
//먼저 오름차순 정렬을 수행한다.
Collections.reverse(strlist);
}
}
import java.util.*;
public class Main {
public static void main(String [] args){
Character [] chr = {'a','z','s'};
List chrlist = Arrays.asList(chr);
Collections.sort(chrlist);
for(int i =0; i<chrlist.size(); i++){
System.out.print(chrlist.get(i)+" ");
}
}
}
Charater에서만 가능, char 불가
import java.util.*;
public class Main {
public static void main(String [] args){
Character [] chr = {'a','z','s'};
List chrlist = Arrays.asList(chr);
Collections.sort(chrlist);
Collections.reverse(chrlist);
}
}
// key 값 기준 정렬
HashMap<Integer, Integer> map = new HashMap<>();
map.put(6, 1);
map.put(1, 2);
map.put(4, 3);
map.put(10, 4);
map.put(7, 5);
Object[] mapKey = map.keySet().toArray();
Arrays.sort(mapKey);
System.out.println("오름차순 정렬");
for (Integer key : map.keySet()) {
System.out.println(key + " : " + map.get(key));
}
Map<String,Integer> testMap = new TreeMap<>();
testMap.put("apple", 1);
testMap.put("pineapple", 2);
testMap.put("orange", 3);
testMap.put("strawberry", 4);
testMap.put("melon", 5);
// 결과 출력
for (Integer nKey : testMap.keySet()) {
System.out.println(nKey + " " + testMap.get(nKey));
}
Map<String,Integer> testMap = new TreeMap<>();
testMap.put("apple", 1);
testMap.put("pineapple", 2);
testMap.put("orange", 3);
testMap.put("strawberry", 4);
testMap.put("melon", 5);
// 키로 정렬
Object[] mapkey = testMap.keySet().toArray();
Arrays.sort(mapkey);
// 정렬안됨
for (Integer nKey : testMap.keySet()) {
System.out.println(nKey + " " + testMap.get(nKey));
}
// 정렬됨
for(int i=0;i<mapkey.length;i++){
System.out.println(mapkey[i]+" "+testMap.get(mapkey[i]));
}
// value 값 기준 정렬
HashMap<Integer, Integer> map2 = new HashMap<>();
map2.put(1, 5);
map2.put(2, 0);
map2.put(3, 3);
map2.put(4, 9);
map2.put(5, 6);
List<Map.Entry<Integer,Integer>> list = new ArrayList<Map.Entry<Integer,Integer>>(map2.entrySet());
Collections.sort(list, new Comparator<>() {
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return o1.getValue().compareTo(o2.getValue()); // 오름차순
// return o1.getValue()-o2.getValue(); // 이 방법도 가능
// return o2.getValue().compareTo(o1.getValue()); // 내림차순
}
});
for(Map.Entry<Integer, Integer> entry : list){
System.out.println(entry.getKey()+" "+entry.getValue());
}
우선순위가 높은 순으로 정렬
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.add(3);
queue.add(5);
queue.add(1);
queue.add(88);
queue.add(8);
while(!queue.isEmpty()){
System.out.print(queue.poll()+" ");
}
PriorityQueue<Integer> que = new PriorityQueue<>(Collections.reverseOrder());
que.add(3);
que.add(5);
que.add(1);
que.add(88);
que.add(8);
while(!que.isEmpty()){
System.out.print(que.poll()+" ");
}
객체 생성하면서 정렬할 때 사용
class Student{
int studentID;
String name;
Student(int studentID, String name){
this.studentID = studentID;
this.name = name;
}
}
Comparable을 상속받아 compareTo를 구현
class Student implements Comparable<Student>{
int studentID;
String name;
public int compareTo(Student s1){
return this.studentID - s1.studentID;
//오름차순 정렬
}
Student(int studentID, String name){
this.studentID = studentID;
this.name = name;
}
}
Student [] students = new Student[3];
students[0] = st1;
students[1] = st2;
students[2] = st3;
List <Student> studentlist = Arrays.asList(students);
//Student 객체로 list 생성한다.
Collections.sort(studentlist);
Student [] dsc = studentlist.toArray(new Student[studentlist.size()]);
//정렬 후 다시 배열로 변환
for(int i =0; i<dsc.length; i++){
System.out.println(dsc[i].studentID+" : "+dsc[i].name);
}
- this.String.compareTo(오브젝트.String)형태로
- 자기 자신과 비교 대상의 문자열을 compareTo()하여 비교한 후 int로 리턴한다.
class Student implements Comparable<Student>{
int studentID;
String name;
public int compareTo(Student s1){
return this.name.compareTo(s1.name);
}
Student(int studentID, String name){
this.studentID = studentID;
this.name = name;
}
}
Comparable을 상속받아 compareTo를 구현
class Student implements Comparable<Student>{
int studentID;
String name;
public int compareTo(Student s1){
return s1.studentID-this.studentID;
//내림차순 정렬
}
Student(int studentID, String name){
this.studentID = studentID;
this.name = name;
}
}
- Collections.sort의 compare를 커스텀하여 사용
- 인스턴스를 배열에 저장 후
Arrays.sort
를 활용하여 정렬한다.
private static class Person {
int age;
String name;
Person(int age, String name){
this.age = age;
this.name= name;
}
public int getAge() {
return age;
}
}
아래 방식은 오버플로우를 유의해야 한다.
Person mom = new Person(31,"msKim");
Person dad = new Person(32,"mrKim");
Person sister = new Person(3,"yuni");
Person me = new Person(27,"zanie");
Person [] fam = new Person[4];
fam[0] = mom;
fam[1] = dad;
fam[2] = sister;
fam[3] = me;
Arrays.sort(fam, new Comparator<Person>(){
public int compare(Person o1, Person o2){
return o1.age-o2.age;
}
});
for(Person p : fam){
System.out.print(p.name+" : "+p.age);
System.out.println();
}
Person의 getAge()를 통해서 비교 가능하다.
Person mom = new Person(31,"msKim");
Person dad = new Person(32,"mrKim");
Person sister = new Person(3,"yuni");
Person me = new Person(27,"zanie");
Person [] fam = new Person[4];
fam[0] = mom;
fam[1] = dad;
fam[2] = sister;
fam[3] = me;
Arrays.sort(fam, Comparator.comparingInt(Person::getAge));
for(Person p : fam){
System.out.print(p.name+" : "+p.age);
System.out.println();
}
Comparator.comparatingInt()
를 사용하면 오버플로우를 방지할 수 있다.
Person mom = new Person(31,"msKim");
Person dad = new Person(32,"mrKim");
Person sister = new Person(3,"yuni");
Person me = new Person(27,"zanie");
Person [] fam = new Person[4];
fam[0] = mom;
fam[1] = dad;
fam[2] = sister;
fam[3] = me;
Arrays.sort(fam, Comparator.comparingInt(p->p.age));
for(Person p : fam){
System.out.print(p.name+" : "+p.age);
System.out.println();
}
아래 방식은
오버플로우
를 유의해야 한다.
Person mom = new Person(31,"msKim");
Person dad = new Person(32,"mrKim");
Person sister = new Person(3,"yuni");
Person me = new Person(27,"zanie");
Person [] fam = new Person[4];
fam[0] = mom;
fam[1] = dad;
fam[2] = sister;
fam[3] = me;
Arrays.sort(fam, new Comparator<Person>(){
public int compare(Person o1, Person o2){
return o2.age- o1.age;
}
});
for(Person p : fam){
System.out.print(p.name+" : "+p.age);
System.out.println();
}
Comparator.comparatingInt()
를 사용하면 오버플로우를 방지할 수 있다.- Person의 getAge()를 통해
comparingInt.reversed()
를 이용하면 내림차순 비교 가능하다.
Person mom = new Person(31,"msKim");
Person dad = new Person(32,"mrKim");
Person sister = new Person(3,"yuni");
Person me = new Person(27,"zanie");
Person [] fam = new Person[4];
fam[0] = mom;
fam[1] = dad;
fam[2] = sister;
fam[3] = me;
Arrays.sort(fam, Comparator.comparingInt(Person::getAge).reversed());
for(Person p : fam){
System.out.print(p.name+" : "+p.age);
System.out.println();
}