Java와 Kotlin에서 retainAll 사용하기

java-&-koltin

What is retainAll Method?

retainAll 메서드는 무엇일까?

RetainAll() 메서드는 지정된 컬렉션에 포함되지 않은 모든 배열 목록 요소를 제거하거나 메서드에 매개 변수로 전달된 컬렉션 목록의 모든 요소와 일치하는 현재 컬렉션 인스턴스의 모든 일치 요소를 유지하는 데 사용되는 메서드이다.

아래의 그림을 보면 이해가 더 쉽다.

collection-method

retain 은 a와 b의 공통된 값만을 제외한 모든 값은 없앨 수 있다.

그래서 어떻게 쓰는 건데?

a, b라는 컬렉션 인스턴스가 존재할 때 a.retainAll(b) 이런 식으로 사용하면 된다.

코틀린 코드를 예제로 봐보자.

fun main(args: Array<String>) {
    val listExampleIntArrayString =
        listRetainAllExample(intArrayOf(1, 2, 2, 1), intArrayOf(2, 2)).map { it.toString() }.toTypedArray()
            .contentToString()
    println("list example int array => " + listExampleIntArrayString)
    val setExampleIntArrayString =
        setRetainAllExample(intArrayOf(1, 2, 2, 1), intArrayOf(2, 2)).map { it.toString() }.toTypedArray()
            .contentToString()
    println("set example int array => " + setExampleIntArrayString)
}

// Runtime 461 ms Memory 43.1 MB
fun listRetainAllExample(nums1: IntArray, nums2: IntArray): IntArray {
    val nums1List = nums1.distinct().toMutableList()
    val nums2List = nums2.distinct().toMutableList()
    nums1List.retainAll(nums2List)
    return nums1List.toIntArray()
}

// Runtime 363 ms Memory 42.4 MB
fun setRetainAllExample(nums1: IntArray, nums2: IntArray): IntArray {
    var nums1Set = nums1.toMutableSet()
    val nums2Set = nums2.toMutableSet()
    nums1Set.retainAll(nums2Set)
    return nums1Set.toIntArray()
}

위의 코드를 보게 되면 [1, 2, 2, 1], [2, 2]를 파라미터로 받아서 중복이 제거된 값들을 추려 IntArray로 다시 반환하는 예제이다.

예제의 코드를 보면 컬렉션 인스턴스인 List와 Set으로 예제를 든다.

단 여기서 List를 통해 retainAll을 할 때 중복 제거를 원하는 경우 distinct()를 사용해 중복제거를 한번 해주고 리스트로 변경 후 retainAll을 실행하였다.

중복이 제거되지 않았을 경우의 결괏값은 다음과 같다.

list example int array => [2, 2]
set example int array => [2]

distinct()를 사용해 중복 제거를 한 결괏값은 다음과 같다.

list example int array => [2]
set example int array => [2]

자바에서 List로 retainAll을 사용한 코드 예제

public class AboutRetainAll {

    public static void main(String[] args) {
        System.out.println(retainAll(new int[]{1, 2, 2, 1}, new int[]{2, 2}));
    }

    public static int[] retainAll(int[] nums1, int[] nums2) {
        Set<Integer> nums1Set = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
        Set<Integer> nums2Set = Arrays.stream(nums2).boxed().collect(Collectors.toSet());
        nums1Set.retainAll(nums2Set);
        return nums1Set.stream().mapToInt(x -> x).toArray();
    }

}

END

이렇게 해서 retainAll 메서드에 알아봤다. 자주 써먹을 수 있길 😁

last-dance

Reference