Algorithm

자바 HashSet을 이용한 교집합, 차집합, 합집합 구하기

OOOooOOoo·2020년 6월 11일·조회 8,265

1. 개요

두개의 Set을 이용하여 교집합, 차집합, 합집합을 구하는 로직이다.

2. 코드

package io.sarc;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class ArraySet {
	public static void main(String[] args) {
		String[] a = { "apple", "banana", "xylophone" };
		String[] b = { "banana", "carrot", "dog", "xray", "xylophone" };

		Set<String> setA = new HashSet<>(Arrays.asList(a));
		Set<String> setB = new HashSet<>(Arrays.asList(b));

		ArraySet arraySet = new ArraySet();
		arraySet.retainAll(setA, setB);
		arraySet.removeAll(setA, setB);
		arraySet.addAll(setA, setB);
		
	}
	
	private void retainAll(Set<String> a, Set<String> b) {
		Set<String> copyA = new HashSet<>();
		copyA.addAll(a);

		copyA.retainAll(b);
		System.out.println(copyA);
	}
	
	private void removeAll(Set<String> a, Set<String> b) {
		Set<String> copyA = new HashSet<>();
		copyA.addAll(a);

		copyA.removeAll(b);
		System.out.println(copyA);
	}
	
	private void addAll(Set<String> a, Set<String> b) {
		Set<String> copyA = new HashSet<>();
		copyA.addAll(a);
		copyA.addAll(b);
		System.out.println(copyA);
	}
}

 

댓글 0

로그인 후 댓글을 남길 수 있습니다.

아직 댓글이 없습니다.