java에서 프로그래밍을 하다 보면 HashMap에서 정렬이 필요할 때가 있다.
key나 value를 기준으로 정렬하는 방법에 대해 알아보자!
// keySet을 list로 가져와 정렬하기
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "A");
map.put(2, "B");
map.put(3, "C");
/**********/
List<Integer> keys = new ArrayList<>(map.keySet());
keys.sort((x, y)->x-y);
// keys.sort((x, y)->y-x); // 내림차순
/**********/
for(Integer key : keys){
System.out.println("key: " + key+" value: "+map.get(key));
}
}
// keySet을 배열로 가져와 정렬하기
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "A");
map.put(2, "B");
map.put(3, "C");
/**********/
Integer[] keys = map.keySet().toArray(new Integer[0]);
Arrays.sort(keys);
// Arrays.sort(keys, (x, y)->y-x); // 내림차순
/**********/
for(Integer key : keys){
System.out.println("key: " + key+" value: "+map.get(key));
}
}
}
//결과
key: 1 value: A
key: 2 value: B
key: 3 value: C
// 내림차순 결과
// 결과
key: 3 value: C
key: 2 value: B
key: 1 value: A
// keySet()을 사용하여 정렬
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(30, "A");
map.put(20, "B");
map.put(100, "C");
List<Integer> keySet = new ArrayList<>(map.keySet());
keySet.sort((x, y)-> map.get(x).compareTo(map.get(y)));
// keySet.sort((x, y)-> map.get(y).compareTo(map.get(x))); // 내림차순
for(Integer key : keySet){
System.out.println("key: "+key+" value: "+map.get(key));
}
}
// entrySet을 사용하여 정렬
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(30, "A");
map.put(20, "B");
map.put(100, "C");
List<Map.Entry<Integer, String>> entrySet = new ArrayList<>(map.entrySet());
Collections.sort(entrySet, new Comparator<Map.Entry<Integer, String>>() {
@Override
public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
return o1.getValue().compareTo(o2.getValue());
// return o2.getValue().compareTo(o1.getValue()); // 내림차순
}
});
for(Map.Entry<Integer, String> entry : entrySet){
System.out.println("key: " + entry.getKey()+" value: "+entry.getValue());
}
}
// 결과
key: 30 value: A
key: 20 value: B
key: 100 value: C
// 내림차순 결과
key: 100 value: C
key: 20 value: B
key: 30 value: A