백준 문제를 풀다가 오답을 맞이하게 된다.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main_7785 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.nextLine(); // 정수 입력 후의 개행 처리
Map<String, String> stfMap = new HashMap<>();
for (int i = 0; i < N; i++) {
String stfs = sc.nextLine();
String[] stf = stfs.split(" ");
String name = stf[0];
String record = stf[1];
stfMap.put(name, record);
}
sc.close();
}
}
Map 에 자료는 넣었는데 이제 어떻게 꺼내는 걸까. (이름 내림차순으로 꺼내야함)
이때 사용되는게 바로 Entry !!
System.out.println("Original HashMap: "+stfMap);
System.out.println("HashMap.entrySet(): " +stfMap.entrySet());
map 과 entrySet()을 사용하여 로그를 찍어보면 다음과 같이 반환하는데
Original HashMap: {Artem=enter, Askar=enter, Baha=leave}
HashMap.entrySet(): [Artem=enter, Askar=enter, Baha=leave]
map
은 키와 값의 형태로 출력한 것이며 객체를 나타내고
entrySet()
은 메서드를 통해 반환된 Set의 내용(컬렉션)을 보여주는것.
Java 에서 Collections.sort()
를 사용하여 정렬을 하려면 일반적으로 List 형태로 정렬할 데이터를 가지고 있어야 한다.
나는 Map
을 정렬해야 하기 때문에
1. entrySet()
을 사용하여 Map 의 각 항목을 Set 형태로 가져온 뒤
2. List 로 변환하여 Collections.sort()
사용해 정렬한다.
따라서 해당 코드를 추가한다.
List<Map.Entry<String, String>> entryList = new ArrayList<>(stfMap.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Entry<String, String> o1, Entry<String, String> o2) {
return o2.getKey().compareTo(o1.getKey());
}
});
compare 메서드는 두개의 Map.Entry<String, String>
객체를 받아와서 비교한다. o1, o2
를 비교하여 정렬 순서를 결정하게 된다.
o2.getKey().compareTo(o1.getKey())
는 두 엔트리의 키를 비교한다.compareTo
메서드는 String
클래스에서 상속받은 메서드로, 문자열을 사전 순으로 비교한다.o2
의 키가 o1
의 키보다 사전 순으로 앞에 위치함.o2
과 o1
의 키가 같음.o2
의 키가 o1
의 키보다 사전 순으로 뒤에 위치함.이를 통해 역순으로 정렬하게 됨.
public class Main_7785 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
sc.nextLine();
Map<String, String> stfMap = new HashMap<>();
for(int i=0; i<N; i++) {
String stfs = sc.nextLine();
String[] stf = stfs.split(" ");
String name = stf[0];
String record= stf[1];
stfMap.put(name, record);
}
List<Map.Entry<String, String>> entryList = new ArrayList<>(stfMap.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Entry<String, String> o1, Entry<String, String> o2) {
return o2.getKey().compareTo(o1.getKey());
}
});
for(Map.Entry<String, String> entry : entryList) {
if(entry.getValue().equals("enter")) {
System.out.println(entry.getKey());
}
}
sc.close();
}
}