[java] 자바에서 JSON 데이터의 중복값 개수 세기

이번에는 자바에서 JSON 데이터에서 중복된 값을 찾고 개수를 세는 방법에 대해 알아보겠습니다.

JSON 데이터는 자바스크립트 객체 표기법으로 데이터를 표현하는 형식입니다. 자바에서는 JSON 데이터를 쉽게 다룰 수 있는 JSON 라이브러리를 제공합니다.

아래는 JSON 데이터의 예시입니다.

{
  "fruits": ["apple", "banana", "apple", "orange", "kiwi"],
  "colors": ["red", "green", "blue", "red", "yellow"]
}

위의 JSON 데이터에서 fruitscolors라는 키에 대한 값들이 있습니다. 이 중에서 중복된 값들을 찾아 개수를 세는 방법을 알아보겠습니다.

우선 JSON 데이터를 자바에서 처리하기 위해 java-json 라이브러리를 사용할 수 있습니다. 이 라이브러리는 다음과 같이 Maven을 통해 추가할 수 있습니다.

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>

라이브러리를 추가하면 다음과 같이 JSON 데이터를 파싱하여 중복값을 찾을 수 있습니다.

import org.json.JSONArray;
import org.json.JSONObject;

public class Main {
    public static void main(String[] args) {
        String jsonStr = "{\"fruits\":[\"apple\",\"banana\",\"apple\",\"orange\",\"kiwi\"],\"colors\":[\"red\",\"green\",\"blue\",\"red\",\"yellow\"]}";

        // JSON 문자열을 JSONObject로 파싱
        JSONObject jsonObj = new JSONObject(jsonStr);

        // fruits 배열에서 중복된 값 개수 세기
        JSONArray fruitsArray = jsonObj.getJSONArray("fruits");
        int fruitsDuplicateCount = countDuplicates(fruitsArray);

        // colors 배열에서 중복된 값 개수 세기
        JSONArray colorsArray = jsonObj.getJSONArray("colors");
        int colorsDuplicateCount = countDuplicates(colorsArray);

        System.out.println("fruits 중복 개수: " + fruitsDuplicateCount);
        System.out.println("colors 중복 개수: " + colorsDuplicateCount);
    }

    private static int countDuplicates(JSONArray jsonArray) {
        int count = 0;
        for (int i = 0; i < jsonArray.length(); i++) {
            for (int j = i + 1; j < jsonArray.length(); j++) {
                if (jsonArray.get(i).equals(jsonArray.get(j))) {
                    count++;
                }
            }
        }
        return count;
    }
}

위의 예시 코드에서 countDuplicates 메서드를 통해 JSON 배열에서 중복된 값의 개수를 세는 로직을 구현하였습니다. 이를 적절히 활용하여 JSON 데이터에서 중복값을 찾고 개수를 세는 작업을 수행할 수 있습니다.


참고 자료: