[Java]List 중복제거와 정렬

List 각 요소의 중복을 제거하고, 정렬해야 하는 경우가 있다.

아래를 참조하자.

package hello;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.*;

public class MyListTest {

    @Test
    void listTest() {
        List<Integer> list = new ArrayList<>(Arrays.asList(1, 3, 2, 3, 4));
        System.out.println("list = " + list); // [1, 3, 2, 3, 4]

        // 중복만 제거, 순서는 보장하지 않는다.
        Set<Integer> uniqueSet = new HashSet<>(list);
        Assertions.assertThat(uniqueSet).contains(1, 2, 3, 4);
        System.out.println("uniqueSet = " + uniqueSet); // [1, 2, 3, 4]

        // 중복제거, 입력순서 유지
        LinkedHashSet<Integer> uniqueList = new LinkedHashSet<>(list);
        Assertions.assertThat(uniqueList).containsExactly(1, 3, 2, 4);
        System.out.println("uniqueList = " + uniqueList); // [1, 3, 2, 4]

        // 중복제거, 오름차순 정렬
        Set<Integer> ascendingSet = new TreeSet<>(list);
        Assertions.assertThat(ascendingSet).containsExactly(1, 2, 3, 4);
        System.out.println("ascendingSet = " + ascendingSet); //  [1, 2, 3, 4]

        // 중복제거, 내림차순 정렬
        TreeSet<Integer> descendingSet = (TreeSet<Integer>) new TreeSet<>(list).descendingSet();
        Assertions.assertThat(descendingSet).containsExactly(4, 3, 2, 1);
        System.out.println("descendingSet = " + descendingSet); // [4, 3, 2, 1]
    }
}

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다