2017-05-10 1 views
1

역순으로 목록을 정렬 한 다음 중복을 제거하려고합니다. 다음 코드를 사용하고 있습니다.목록을 역순으로 정렬하고 중복을 제거하십시오.

public static void main(String[] args) { 
    List<Integer> list = new ArrayList<>(); 
    list.add(3); 
    list.add(3); 
    list.add(2); 
    list.add(3); 
    list.add(2); 
    Collections.sort(list, Collections.reverseOrder()); 
    System.out.println(list); 
    Set<Integer> set = new HashSet<>(list); 
    System.out.println(set); 
} 

잘 작동하지만 세트로 변환하면 순서가 다시 변경됩니다. 순서를 대신 HashSet의이 TreeSet의를 사용의

+0

LinkedHashSet 사용 –

+0

HashSet은 삽입 순서를 유지하지 않습니다 **. 그렇게 간단합니다. – GhostCat

답변

2

HashSet 대신 LinkedHashSet을 사용하십시오. 순서 보장이없는 정상 세트 달리

Set<Integer> set = new LinkedHashSet<>(list); 

LinkedHashSet들 신청서 시행. 이미 목록을 정렬 했으므로 TreeSet에서 제공하는 추가 혜택 (자연 주문이나 주문한 주문을 기반으로 한 주문)은 필요하지 않습니다.

관련 문제