[자바 컬렉션과 Stream] 77. Set

김건우's avatar
Feb 19, 2025
[자바 컬렉션과 Stream] 77. Set
💡
순서에는 상관없이 데이터를 정하고 싶은 경우 사용
가장 대표적인 컬렉션 HashSet

문자열을 Set에 저장

package ex16; // 문자열을 Set에 저장하기 import java.util.HashSet; public class SetTest01 { public static void main(String[] args) { HashSet<String> set = new HashSet<String>(); set.add("Apple"); set.add("Grape"); set.add("Pear"); set.add("Mango"); set.add("Ham"); set.add("Ham"); System.out.println(set); if (set.contains("Ham")) { System.out.println("Ham도 포함되어 있음"); } } }
notion image

합집합, 교집합

package ex16; // 합집합과 교집합 계산 import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class SetTest02 { public static void main(String[] args) { Set<Integer> S1 = new HashSet<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 9)); Set<Integer> S2 = new HashSet<Integer>(Arrays.asList(2, 4, 6, 8)); S1.addAll(S2); System.out.println(S1); S1.retainAll(S2); System.out.println(S1); } }
notion image

중복된 단어 검출하기

package ex16; // 중복된 단어 검출하기 import java.util.HashSet; import java.util.Set; public class FindDupplication { public static void main(String[] args) { Set<String> set = new HashSet<String>(); String[] arr = {"사과", "사과", "바나나", "토마토"}; for (String s : arr) if (!set.add(s)) // 집합에 추가되지 않으면 중복된 단어이다. System.out.println("중복된 단어: " + s); System.out.println(set.size() + "중복되지 않은 단어: " + set); } }
notion image
Share article

gunwoo