본문으로 바로가기
반응형

Map을 사용할 수도 있고, 다른 여러가지 자료형을 통해 중복값을 제거하는 방법은 많다.

여기서는 ArrayList를 다룰때, 중복값을 제거하고 그 제거한 값의 원래 개수를 리턴하는 메서드를 다룬다.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> inputList = new ArrayList<>();
        inputList.add("apple");
        inputList.add("orange");
        inputList.add("apple");
        inputList.add("banana");
        inputList.add("orange");
        inputList.add("apple");

        ArrayList<String> resultList = removeDuplicatesAndCount(inputList);
        System.out.println(resultList);
    }

    public static ArrayList<String> removeDuplicatesAndCount(ArrayList<String> inputList) {
        ArrayList<String> resultList = new ArrayList<>();
        HashMap<String, Integer> countMap = new HashMap<>();

        for (String element : inputList) {
            countMap.put(element, countMap.getOrDefault(element, 0) + 1);
        }

        for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
            resultList.add(entry.getKey() + " - " + entry.getValue());
        }

        return resultList;
    }
}

위 코드를 실행하면, 요소의 대표값인 apple, orange, banana 값만 남고 중복제거 하기 전 개수인 3,2,1 리턴된다.

결과는 다음과 같다.

[apple - 3, orange - 2, banana - 1]

반응형