반응형
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
반응형
'JAVA' 카테고리의 다른 글
JDBC API 연습문제 (0) | 2020.04.02 |
---|---|
모듈 기술자 (Java 11 버전 이후) (3) | 2019.12.18 |
Map 컬렉션 (0) | 2019.05.22 |
Set 컬렉션 (0) | 2019.05.22 |
List 컬렉션 (0) | 2019.05.22 |