Menu
Coddy logo textTech

수학 - HashSet의 합집합

Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨 — 59개 중 29번째.

두 집합의 합집합은 어느 집합에든 속하는 모든 원소를 포함하는 새로운 집합입니다. Java에서 두 HashSet의 합집합을 계산하려면 addAll() 메서드를 사용할 수 있습니다. 이 메서드는 한 집합의 모든 원소를 다른 집합에 추가합니다(중복은 무시).

먼저, 두 개의 새로운 HashSet을 생성하세요:

HashSet<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
HashSet<Integer> set2 = new HashSet<>();
set2.add(2);
set2.add(3);

두 번째 집합의 요소를 합집합 집합에 추가하려면 addAll() 메서드를 사용하세요.

// First, create a new HashSet with set1
HashSet<Integer> unionSet = new HashSet<>(set1);
unionSet.addAll(set2); // Then, add all elements from set2
System.out.println("Union: " + unionSet);
// Output: [1, 2, 3] (order may vary)
challenge icon

챌린지

쉬움

입력으로 두 개의 정수 HashSet을 받는 <strong>unionSets</strong>라는 메서드를 생성하세요. 합집합을 계산하고 다음 형식으로 출력하세요:

Union: [1, 2, 3]

치트 시트

두 집합의 합집합은 두 집합 중 어느 하나에 속하는 모든 원소를 포함합니다. 두 HashSet의 합집합을 계산하기 위해 addAll()을 사용하세요:

HashSet<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
HashSet<Integer> set2 = new HashSet<>();
set2.add(2);
set2.add(3);

// Create union by copying first set and adding all elements from second
HashSet<Integer> unionSet = new HashSet<>(set1);
unionSet.addAll(set2);
System.out.println("Union: " + unionSet);
// Output: [1, 2, 3] (order may vary)

직접 해보기

import java.util.HashSet;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

public class Main {
    public static void unionSets(HashSet<Integer> set1, HashSet<Integer> set2) {
        // 여기에 코드를 작성하세요
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 첫 번째 집합을 나타내는 JSON 문자열 읽기 (예: [1,2])
        String set1String = scanner.nextLine();
        // 두 번째 집합을 나타내는 JSON 문자열 읽기 (예: [2,3])
        String set2String = scanner.nextLine();

        Type setType = new TypeToken<HashSet<Integer>>(){}.getType();
        HashSet<Integer> set1 = new Gson().fromJson(set1String, setType);
        HashSet<Integer> set2 = new Gson().fromJson(set2String, setType);
        
        unionSets(set1, set2);
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

논리와 흐름의 모든 레슨