JAVA
"HashMap"의 "Value" 기준 정렬
BSHwan
2019. 8. 27. 17:23
반응형
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
import java.util.List;
import java.util.Comparator;
import java.util.ArrayList;
public class Main{
public static void main(String[] args){
Map<Integer, Double> map = new HashMap<Integer, Double>();
map.put(1, 0.8);
map.put(2, 0.3);
map.put(3, 0.6);
map.put(4, 0.9);
map.put(5, 0.2);
List<Integer> keySetList = new ArrayList<>(map.keySet());
// 오름차순
System.out.println("------value 오름차순------");
Collections.sort(keySetList, (o1, o2) -> (map.get(o1).compareTo(map.get(o2))));
for(Integer key : keySetList) {
System.out.println("key : " + key + " / " + "value : " + map.get(key));
}
System.out.println();
// 내림차순
System.out.println("------value 내림차순------");
Collections.sort(keySetList, (o1, o2) -> (map.get(o2).compareTo(map.get(o1))));
for(Integer key : keySetList) {
System.out.println("key : " + key + " / " + "value : " + map.get(key));
}
}
}
[ 결과값 ]
------value 오름차순------
key : 5 / value : 0.2
key : 2 / value : 0.3
key : 3 / value : 0.6
key : 1 / value : 0.8
key : 4 / value : 0.9
------value 내림차순------
key : 4 / value : 0.9
key : 1 / value : 0.8
key : 3 / value : 0.6
key : 2 / value : 0.3
key : 5 / value : 0.2
반응형