본문 바로가기
JAVA

[JAVA] 자바 부분집합, 교집합, 합집합, 차집합

by Minius 2018. 2. 8.
반응형
package edu.collection;

import java.util.HashSet;
import java.util.Iterator;

public class CollectionEx3 {

	public static void main(String[] args) {
		HashSet hs1 = new HashSet();
		hs1.add("a"); hs1.add("b"); hs1.add("c");
		HashSet hs2 = new HashSet();
		hs2.add("c"); hs2.add("d"); hs2.add("e");
		HashSet hs3 = new HashSet();
		hs3.add("a"); hs3.add("b");

		// Case_1 부분집합
		System.out.println("부분집합");
		System.out.println(hs1.containsAll(hs2));
		//hs2가 hs1의 부분집합인 경우 return true;
		System.out.println(hs1.containsAll(hs3));
		//hs3가 hs1의 부분집합인 경우 return true;
		Iterator it4= hs1.iterator();
		while(it4.hasNext()){
			System.out.println(it4.next());
		}
		
		// Case_2 교집합
		System.out.println("교집합");
		System.out.println(hs1.retainAll(hs3));
		Iterator it3= hs1.iterator();
		while(it3.hasNext()){
			System.out.println(it3.next());
		}
		
		// Case_3 합집합
		System.out.println("합집합");
		System.out.println(hs1.addAll(hs2));
		Iterator it2= hs1.iterator();
		while(it2.hasNext()){
			System.out.println(it2.next());
		}
		
		// Case_4 차집합
		System.out.println("차집합");
		System.out.println(hs1.removeAll(hs1));
		Iterator it1= hs2.iterator();
		while(it1.hasNext()){
			System.out.println(it1.next());
		}
	}

}

 

댓글