Java 8에서 키와 값으로 HashMap을 정렬하는 방법 – 전체 자습서
게시 됨: 2020-09-18
Java 8에서 – 지도를 정렬하는 방법은 무엇입니까?
Crunchify에서 우리는 거의 400개의 자바 튜토리얼을 작성했으며 이것은 Java8 카테고리에 추가된 것입니다.
저는 Java 컬렉션을 좋아하고 Map and List, LinkedList, JSONArray 등을 통해 반복하는 방법에 대한 여러 자습서를 가지고 있습니다.
이 튜토리얼에서는 Java8에서 키와 값으로 HashMap을 정렬하는 가장 좋은 방법을 살펴보겠습니다.
시작하자:
- CrunchifySortMapByKeyValueJava8.java 클래스를 생성하겠습니다.
- HashMap<String, Integer> crunchifyMap을 만들고 이것이 키와 값으로 정렬하는 데 사용할 것입니다.
-
For KEY
: 목록에서 임의의 회사를 추가할 것입니다.- 패턴: 1에서 10 사이의 임의의 숫자 + (-) + 목록에서 1개 회사
- 회사 목록: crunchify.com, google.com, twitter.com
-
For VALUE
: 1에서 50 사이의 임의의 숫자 하나를 추가합니다. - 키 맵으로 정렬되고 값 맵으로 정렬된 원본 맵을 인쇄합니다.
지도.진입.
comparingByKey()
는 키에 대해 자연 순서로 Map.Entry를 비교하는 비교기를 반환합니다.지도.진입.
comparingByValue()
는 값에 대해 자연스러운 순서로 Map.Entry를 비교하는 비교기를 반환합니다.
다음은 완전한 Java 코드입니다.
아래 코드에 언급된 두 가지 질문을 주의 깊게 살펴보십시오. 프로젝트에서 사용하려는 경우를 대비하여 간단한 유틸리티입니다.
- ArrayList에서 Random 값을 얻는 방법은 무엇입니까?
- Java 8에서 HashMap을 반복하는 방법은 무엇입니까?
CrunchifySortMapByKeyValueJava8.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
package crunchify . com . tutorial ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . LinkedHashMap ; import java . util . Map ; import java . util . Random ; import java . util . stream . Stream ; /** * @author Crunchify.com * * Best way to sort HashMap by Key and Value in Java8 - Tutorial by App Shah * */ public class CrunchifySortMapByKeyValueJava8 { private static final Random crunchifyRandom = new Random ( ) ; public static void main ( String [ ] argv ) { Map < String , Integer > crunchifyMap = new HashMap < > ( ) ; // Let's first create companies ArrayList ArrayList <String> companies = new ArrayList < > ( ) ; companies . add ( "Crunchify.com" ) ; companies . add ( "Google.com" ) ; companies . add ( "Twitter.com" ) ; // Let's add 10 entries to HashMap crunchifyMap for ( int i = 1 ; i < = 10 ; ++ i ) { // How to get Random value from ArrayList? String company = companies . get ( crunchifyRandom . nextInt ( companies . size ( ) ) ) ; // Basically we are creating // Key with pattern: 1-Crunchify, 5-Google, and so on... // Random Value: Number between 1 to 50 crunchifyMap . put ( crunchifyRandom . nextInt ( 10 ) + "-" + company , crunchifyRandom . nextInt ( 50 ) ) ; } crunchifyLog ( "~~~~~~~~~~~~~~Original HashMap (crunchifyMap value)~~~~~~~~~~~~~~" ) ; crunchifyLog ( crunchifyMap ) ; crunchifyLog ( "\n~~~~~~~~~~~~~~Updated HashMap after Sorting by Key~~~~~~~~~~~~~~" ) ; // Map: An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. Map < String , Integer > key = crunchifySortByKey ( crunchifyMap ) ; iterateThroughHashMapJava8 ( key ) ; crunchifyLog ( "\n~~~~~~~~~~~~~~Updated HashMap after Sorting by Value~~~~~~~~~~~~~~" ) ; Map < String , Integer > value = crunchifySortByValue ( crunchifyMap ) ; iterateThroughHashMapJava8 ( value ) ; } // Simple Log Statement private static void crunchifyLog ( Object string ) { System . out . println ( string ) ; } // How to Iterate through HashMap in Java 8? private static void iterateThroughHashMapJava8 ( Map < String , Integer > crunchifyMap ) { crunchifyMap . forEach ( ( k , v ) - > { System . out . println ( "Key: " + k + "\t\t\t Value: " + v ) ; } ) ; } // Let's sort HashMap by Key // Comparable: This interface imposes a total ordering on the objects of each class that implements it. // This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method. public static < K extends Comparable < ? super K > , V > Map < K , V > crunchifySortByKey ( Map < K , V > crunchifyMap ) { Map < K , V > crunchifyResult = new LinkedHashMap < > ( ) ; Stream < Map . Entry < K , V > > sequentialStream = crunchifyMap . entrySet ( ) . stream ( ) ; // comparingByKey() returns a comparator that compares Map.Entry in natural order on key. sequentialStream . sorted ( Map . Entry . comparingByKey ( ) ) . forEachOrdered ( c - > crunchifyResult . put ( c . getKey ( ) , c . getValue ( ) ) ) ; return crunchifyResult ; } // Let's sort HashMap by Value public static < K , V extends Comparable < ? super V > > Map < K , V > crunchifySortByValue ( Map < K , V > crunchifyMap ) { Map < K , V > crunchifyResult = new LinkedHashMap < > ( ) ; // Stream: A sequence of elements supporting sequential and parallel aggregate operations. // The following example illustrates an aggregate operation using Stream and IntStream. Stream < Map . Entry < K , V > > sequentialStream = crunchifyMap . entrySet ( ) . stream ( ) ; // comparingByValue() returns a comparator that compares Map.Entry in natural order on value. // sorted(): Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. sequentialStream . sorted ( Map . Entry . comparingByValue ( ) ) . forEachOrdered ( c - > crunchifyResult . put ( c . getKey ( ) , c . getValue ( ) ) ) ; // getValue(): Returns the value corresponding to this entry. If the mapping has been removed from the backing map (by the iterator's remove operation), the results of this call are undefined. // getKey(): Returns the key corresponding to this entry. return crunchifyResult ; } } |
Eclipse 콘솔 출력:
위의 프로그램을 Java Application으로 실행하면 아래와 같은 결과를 볼 수 있습니다.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Original HashMap ( crunchifyMap value ) ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ { 9 - Google . com = 36 , 6 - Twitter . com = 17 , 3 - Google . com = 39 , 2 - Twitter . com = 43 , 5 - Crunchify . com = 2 , 8 - Google . com = 5 , 8 - Crunchify . com = 47 , 5 - Google . com = 10 , 7 - Google . com = 3 } ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Updated HashMap after Sorting by Key ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Key : 2 - Twitter . com Value : 43 Key : 3 - Google . com Value : 39 Key : 5 - Crunchify . com Value : 2 Key : 5 - Google . com Value : 10 Key : 6 - Twitter . com Value : 17 Key : 7 - Google . com Value : 3 Key : 8 - Crunchify . com Value : 47 Key : 8 - Google . com Value : 5 Key : 9 - Google . com Value : 36 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Updated HashMap after Sorting by Value ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Key : 5 - Crunchify . com Value : 2 Key : 7 - Google . com Value : 3 Key : 8 - Google . com Value : 5 Key : 5 - Google . com Value : 10 Key : 6 - Twitter . com Value : 17 Key : 9 - Google . com Value : 36 Key : 3 - Google . com Value : 39 Key : 2 - Twitter . com Value : 43 Key : 8 - Crunchify . com Value : 47 |
위 프로그램을 실행하는 데 문제가 있으면 알려주십시오.