상세 컨텐츠

본문 제목

[JAVA] SortedMap - TreeMap 사용법

Spring/JAVA

by Chan.94 2022. 7. 18. 08:43

본문

반응형

SortedMap

Map 중에서도 특별히 Key 값에 따라 정렬이 되는 Map인 SortedMap

SortedMap은 key의 값이 Integer, Double, String 등과 같이 비교 가능한(Comparable) 타입이거나, SortedMap을 생성하는 시기에 별도의 Comparator를 등록해서 정렬할 수 있다.

 

TreeMap

Sortedmap은 인터페이스며, 해당 인터페이스를 모두 구현한 클래스가 TreeMap

 

Comparable과 Comparator에 대한 내용은 [JAVA] Comparable과 Comparator 포스팅을 참고바란다.


비교 가능한(Comparable) 타입인 경우

SortedMap<Integer, Integer> map = new TreeMap<>();                                   
map.put(3, 100);                                                                     
map.put(2, 200);                                                                     
map.put(1, 300);                                                                     
                                                                                     
for(Entry entry : map.entrySet()) {                                                  
	System.out.println("key : " + entry.getKey() + "   value : " + entry.getValue());
}
key : 1   value : 300
key : 2   value : 200
key : 3   value : 100

 

별도의 Comparator를 등록

SortedMap<Integer, Integer> map1 = new TreeMap<Integer, Integer>(new DescendingComparator());
map1.put(3, 100);                                                                            
map1.put(2, 200);                                                                            
map1.put(1, 300);                                                                            
                                                                                                    
for(Entry entry : map1.entrySet()) {                                                         
	System.out.println("key : " + entry.getKey() + "   value : " + entry.getValue());        
}
class DescendingComparator implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        if(o1 < o2) return 1;
        else if(o1 == o2) return 0;
        else return -1;
    }
}
key : 3   value : 100
key : 2   value : 200
key : 1   value : 300
반응형

관련글 더보기

댓글 영역

>