logo

Java에서 HashMap을 정렬하는 방법

Java HashMap은 기본적으로 순서를 유지하지 않습니다. HashMap을 정렬해야 하는 경우 요구 사항에 따라 명시적으로 정렬합니다. Java는 키와 값을 기준으로 HashMap을 정렬하는 옵션을 제공합니다. 이번 섹션에서는 HashMap을 키와 값에 따라 정렬하는 방법을 알아봅니다.

  • 키를 기준으로 HashMap 정렬
  • 값을 기준으로 HashMap 정렬

키를 기준으로 HashMap 정렬

HashMap을 키별로 정렬하는 방법은 다음과 같습니다.

  • 사용하여 트리맵
  • 사용하여 LinkedHashMap

LinkedHashMap을 사용할 때는 다음 프로세스를 따라야 합니다.

LinkedHashMap을 사용하려면 키를 설정해야 합니다. Set을 List로 변환하고 목록을 정렬한 다음 정렬된 목록을 LinkedHashMap에 동일한 순서로 추가합니다. 예제에서 수행한 것과 동일한 프로세스 값을 기준으로 HashMap 정렬 .

키를 기준으로 HashMap을 정렬하는 예

다음 예제에서는 TreeMap 생성자를 사용하여 요소를 정렬하고 HashMap 클래스의 객체를 인수로 전달합니다. 이것은 HashMap을 키별로 정렬하는 가장 간단한 방법입니다.

 import java.util.Map; import java.util.HashMap; import java.util.TreeMap; import java.util.Iterator; public class SortHashMapByKeys { public static void main(String args[]) { //implementation of HashMap HashMap hm=new HashMap(); //addding keys and values to HashMap hm.put(23, 'Yash'); hm.put(17, 'Arun'); hm.put(15, 'Swarit'); hm.put(9, 'Neelesh'); Iterator it = hm.keySet().iterator(); System.out.println('Before Sorting'); while(it.hasNext()) { int key=(int)it.next(); System.out.println('Roll no: '+key+' name: '+hm.get(key)); } System.out.println('
'); Map map=new HashMap(); System.out.println('After Sorting'); //using TreeMap constructor to sort the HashMap TreeMap tm=new TreeMap (hm); Iterator itr=tm.keySet().iterator(); while(itr.hasNext()) { int key=(int)itr.next(); System.out.println('Roll no: '+key+' name: '+hm.get(key)); } } } 

산출:

 Before Sorting Roll no: 17 name: Arun Roll no: 23 name: Yash Roll no: 9 name: Neelesh Roll no: 15 name: Swarit After Sorting Roll no: 9 name: Neelesh Roll no: 15 name: Swarit Roll no: 17 name: Arun Roll no: 23 name: Yash 

비교기 인터페이스를 사용하여 값으로 HashMap 정렬

Java에서는 직접 메서드를 사용할 수 없기 때문에 HashMap을 값별로 정렬하는 것이 복잡합니다. HashMap을 값별로 정렬하려면 비교기 . 값을 기준으로 두 요소를 비교합니다.

그런 다음 맵에서 요소 집합을 가져오고 집합을 목록으로 변환합니다. 사용 Collections.sort(목록) 사용자 정의된 비교기를 전달하여 요소 목록을 값별로 정렬하는 메서드입니다. 이제 새로 생성하세요. LinkedHashMap 정렬된 요소를 거기에 복사합니다. 부터 LinkedHashMap 매핑의 삽입 순서를 보장합니다. 값이 정렬된 순서로 정렬된 HashMap을 얻습니다.

후보 키

HashMap을 키와 값으로 정렬하는 것에는 약간의 차이가 있는데, 중복 값은 가질 수 있지만 중복 키는 가질 수 없다는 것입니다. TreeMap은 요소를 키별로 정렬하기 때문에 TreeMap을 사용하여 값을 정렬할 수 없습니다.

값을 기준으로 HashMap을 정렬하는 예

 import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class SortHashMapValue { public static void main(String[] args) { //implementing HashMap HashMap hm = new HashMap(); hm.put(6, 'Tushar'); hm.put(12, 'Ashu'); hm.put(5, 'Zoya'); hm.put(78, 'Yash'); hm.put(10, 'Praveen'); hm.put(67, 'Boby'); hm.put(1, 'Ritesh'); System.out.println('Before Sorting:'); Set set = hm.entrySet(); Iterator iterator = set.iterator(); while(iterator.hasNext()) { Map.Entry map = (Map.Entry)iterator.next(); System.out.println('Roll no: '+map.getKey()+' Name: '+map.getValue()); } Map map = sortValues(hm); System.out.println('
'); System.out.println('After Sorting:'); Set set2 = map.entrySet(); Iterator iterator2 = set2.iterator(); while(iterator2.hasNext()) { Map.Entry me2 = (Map.Entry)iterator2.next(); System.out.println('Roll no: '+me2.getKey()+' Name: '+me2.getValue()); } } //method to sort values private static HashMap sortValues(HashMap map) { List list = new LinkedList(map.entrySet()); //Custom Comparator Collections.sort(list, new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry) (o1)).getValue()).compareTo(((Map.Entry) (o2)).getValue()); } }); //copying the sorted list in HashMap to preserve the iteration order HashMap sortedHashMap = new LinkedHashMap(); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry) it.next(); sortedHashMap.put(entry.getKey(), entry.getValue()); } return sortedHashMap; } } 

산출:

 Before Sorting: Roll no: 1 Name: Ritesh Roll no: 67 Name: Boby Roll no: 5 Name: Zoya Roll no: 6 Name: Tushar Roll no: 10 Name: Praveen Roll no: 12 Name: Ashu Roll no: 78 Name: Yash After Sorting: Roll no: 12 Name: Ashu Roll no: 67 Name: Boby Roll no: 10 Name: Praveen Roll no: 1 Name: Ritesh Roll no: 6 Name: Tushar Roll no: 78 Name: Yash Roll no: 5 Name: Zoya