소개
HashMap 은 키 - 값 쌍을 저장하는 컬렉션입니다. 하지만 특정 순서로 키 - 값 쌍을 저장하지 않으며, 요소의 삽입 순서를 유지하지 않습니다. 데이터를 정렬된 방식으로 보고 싶은 경우가 있을 수 있습니다. 이러한 경우 HashMap 을 정렬해야 합니다.
HashMap 은 키 - 값 쌍을 저장하는 컬렉션입니다. 하지만 특정 순서로 키 - 값 쌍을 저장하지 않으며, 요소의 삽입 순서를 유지하지 않습니다. 데이터를 정렬된 방식으로 보고 싶은 경우가 있을 수 있습니다. 이러한 경우 HashMap 을 정렬해야 합니다.
먼저, HashMap 을 정렬하는 코드를 작성하기 위해 새로운 Java 파일을 생성해야 합니다. 터미널을 열고 파일을 생성하려는 디렉토리로 이동합니다. 다음 명령을 사용하여 HashMapSortDemo.java라는 새 파일을 생성합니다.
touch HashMapSortDemo.java
Collections.sort() 메서드를 사용하여 HashMap 을 키로 정렬할 수 있습니다. 아래 코드를 따르세요.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;
public class HashMapSortDemo {
public static void main(String args[]) {
HashMap<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("one", 1);
unsortedMap.put("two", 2);
unsortedMap.put("three", 3);
unsortedMap.put("four", 4);
unsortedMap.put("five", 5);
System.out.println("Printing the Unsorted HashMap");
for(Entry<String, Integer> e : unsortedMap.entrySet()) {
System.out.println(e.getKey() + "-->" + e.getValue());
}
ArrayList<String> sortedList = new ArrayList<>(unsortedMap.keySet());
Collections.sort(sortedList);
System.out.println("\nPrinting the Alphabetically Sorted Keys");
for(String s : sortedList) {
System.out.println(s + "-->" + unsortedMap.get(s));
}
}
}
위 코드는 Collections.sort() 메서드를 사용하여 HashMap 을 키로 정렬합니다.
다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac HashMapSortDemo.java && java HashMapSortDemo
Collections.sort() 메서드를 사용하여 HashMap 을 값으로 정렬할 수 있습니다. 아래 코드를 따르세요.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;
public class HashMapSortDemo {
public static void main(String args[]) {
HashMap<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("one", 1);
unsortedMap.put("two", 2);
unsortedMap.put("three", 3);
unsortedMap.put("four", 4);
unsortedMap.put("five", 5);
System.out.println("Printing the Unsorted HashMap");
for(Entry<String, Integer> e : unsortedMap.entrySet()) {
System.out.println(e.getKey() + "-->" + e.getValue());
}
ArrayList<Integer> sortedList = new ArrayList<>(unsortedMap.values());
Collections.sort(sortedList);
System.out.println("\nPrinting the Sorted Values");
for(Integer i : sortedList) {
System.out.println(i);
}
}
}
위 코드는 Collections.sort() 메서드를 사용하여 HashMap 을 값으로 정렬합니다.
다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac HashMapSortDemo.java && java HashMapSortDemo
TreeMap 을 사용하여 HashMap 을 키로 정렬할 수 있습니다. TreeMap 은 자동으로 키 - 값 쌍을 정렬된 순서 (키로 정렬) 로 저장합니다. 아래 코드를 따르세요.
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeMap;
public class HashMapSortDemo {
public static void main(String args[]) {
HashMap<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("one", 1);
unsortedMap.put("two", 2);
unsortedMap.put("three", 3);
unsortedMap.put("four", 4);
unsortedMap.put("five", 5);
System.out.println("Printing the Unsorted HashMap");
for(Entry<String, Integer> e : unsortedMap.entrySet()) {
System.out.println(e.getKey() + "-->" + e.getValue());
}
TreeMap<String, Integer> sortedMap = new TreeMap<>(unsortedMap);
System.out.println("\nPrinting the Sorted TreeMap");
for(Entry<String, Integer> e : sortedMap.entrySet()) {
System.out.println(e.getKey() + "-->" + e.getValue());
}
}
}
위 코드는 TreeMap 을 사용하여 HashMap 을 키로 정렬합니다.
다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac HashMapSortDemo.java && java HashMapSortDemo
TreeSet 을 사용하여 HashMap 을 값으로 정렬할 수 있습니다. TreeSet 또한 데이터를 정렬된 순서 (값으로 정렬) 로 저장합니다. 아래 코드를 따르세요.
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeSet;
public class HashMapSortDemo {
public static void main(String args[]) {
HashMap<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("one", 1);
unsortedMap.put("two", 2);
unsortedMap.put("three", 3);
unsortedMap.put("four", 4);
unsortedMap.put("five", 5);
unsortedMap.put("fourteen", 4);
unsortedMap.put("fifteen", 5);
unsortedMap.put("twenty", 2);
System.out.println("Printing the Unsorted HashMap");
for(Entry<String, Integer> e : unsortedMap.entrySet()) {
System.out.println(e.getKey() + "-->" + e.getValue());
}
TreeSet<Integer> sortedSet = new TreeSet<>(unsortedMap.values());
System.out.println("\nThe sorted values are: " + sortedSet);
}
}
위 코드는 TreeSet 을 사용하여 HashMap 을 값으로 정렬합니다.
다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac HashMapSortDemo.java && java HashMapSortDemo
Java Streams 와 Lambda 표현식을 사용하여 한 줄의 코드로 HashMap 을 정렬할 수 있습니다. 아래 코드를 따르세요.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Stream;
public class HashMapSortDemo {
public static void main(String args[]) {
HashMap<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("one", 1);
unsortedMap.put("two", 2);
unsortedMap.put("three", 3);
unsortedMap.put("four", 4);
unsortedMap.put("five", 5);
System.out.println("Printing the Unsorted HashMap");
for(Entry<String, Integer> e : unsortedMap.entrySet()) {
System.out.println(e.getKey() + "-->" + e.getValue());
}
Stream<Entry<String, Integer>> sortedStream = unsortedMap.entrySet()
.stream()
.sorted(Map.Entry.<String, Integer>comparingByKey());
System.out.println("\nPrinting the Sorted Key-Value Pairs");
sortedStream.forEach(System.out :: println);
}
}
위 코드는 Java Streams 와 Lambda 표현식을 사용하여 HashMap 을 정렬합니다.
다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac HashMapSortDemo.java && java HashMapSortDemo
Java Streams 와 Lambda 표현식을 사용하여 HashMap 을 값으로 정렬할 수도 있습니다. 아래 코드를 따르세요.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Stream;
public class HashMapSortDemo {
public static void main(String args[]) {
HashMap<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("one", 1);
unsortedMap.put("two", 2);
unsortedMap.put("three", 3);
unsortedMap.put("four", 4);
unsortedMap.put("five", 5);
System.out.println("Printing the Unsorted HashMap");
for(Entry<String, Integer> e : unsortedMap.entrySet()) {
System.out.println(e.getKey() + "-->" + e.getValue());
}
Stream<Entry<String, Integer>> sortedStream = unsortedMap.entrySet()
.stream()
.sorted(Map.Entry.<String, Integer>comparingByValue());
System.out.println("\nPrinting the Sorted Key-Value Pairs");
sortedStream.forEach(System.out :: println);
}
}
위 코드는 Java Streams 와 Lambda 표현식을 사용하여 HashMap 을 값으로 정렬합니다.
다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac HashMapSortDemo.java && java HashMapSortDemo
Google 의 Guava 라이브러리는 ImmutableSortedMap 클래스를 제공합니다. 이 클래스의 copyOf() 메서드를 사용하여 HashMap 을 정렬할 수 있습니다. 아래 코드를 따르세요.
import java.util.HashMap;
import java.util.Map.Entry;
import com.google.common.collect.ImmutableSortedMap;
public class HashMapSortDemo {
public static void main(String args[]) {
HashMap<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("one", 1);
unsortedMap.put("two", 2);
unsortedMap.put("three", 3);
unsortedMap.put("four", 4);
unsortedMap.put("five", 5);
System.out.println("Printing the Unsorted HashMap");
for (Entry<String, Integer> e : unsortedMap.entrySet()) {
System.out.println(e.getKey() + "-->" + e.getValue());
}
ImmutableSortedMap<String, Integer> sortedMap = ImmutableSortedMap.copyOf(unsortedMap);
System.out.println("\nPrinting the Sorted ImmutableSortedMap");
System.out.println(sortedMap);
}
}
위 코드는 Google 의 Guava 라이브러리를 사용하여 HashMap 을 정렬합니다.
다음 명령을 사용하여 코드를 컴파일하고 실행합니다.
javac -cp ".:guava-30.1.1-jre.jar" HashMapSortDemo.java && java -cp ".:guava-30.1.1-jre.jar" HashMapSortDemo
마지막으로, 다음 명령을 사용하여 HashMapSortDemo.java 파일을 삭제합니다.
rm HashMapSortDemo.java
이 랩에서는 HashMap 을 키 또는 값으로 정렬하는 방법을 살펴보았습니다. HashMap 정렬을 위해 Collections.sort(), TreeMap, TreeSet, Java Streams 및 Lambda 표현식, 그리고 Google 의 Guava 라이브러리와 같은 다양한 방법을 사용했습니다. 또한 각 방법의 사용 사례와 Java 에서 HashMap 을 효율적으로 정렬하는 코드를 작성하는 방법에 대해 배웠습니다.