passion and relax

[JAVA] 배열(Array)을 Set으로 변경 본문

프로그래밍

[JAVA] 배열(Array)을 Set으로 변경

Grab Java 2024. 3. 19. 16:23

자바에서 Array를 Set으로 변경하는 방법들

 

변경하고자 하는 배열

String[] arrayFruit = {"apple", "banana", "kiwi", "apple"};

 

 

 

다이아몬드 연산자 이용

Set<String> setFruit = new HashSet<>(Arrays.asList(arrayFruit));

 

 

Set.copyOf()

Set<String> setFruit = Set.copyOf(Arrays.asList(arrayFruit));

 

 

Collections.addAll()

Set<String> setFruit = new HashSet<String>();
Collections.addAll(setFruit, arrayFruit);

 

 

구글 commons 이용

import com.google.common.collect.Sets;
Set<String> setFruit = Sets.newHashSet(arrayFruit);

 

 

Collectors 이용

import java.util.stream.Collectors;
Set<String> setFruit = Arrays.stream(arrayFruit).collect(Collectors.toSet());

 

 

Stream 이용

import java.util.stream.Stream;
Set<String> setFruit = Stream.of(arrayFruit).collect(Collectors.toCollection(HashSet::new));

 

 

아파치 commons 이용

import org.apache.commons.collections4.CollectionUtils;
Set<String> setFruit = new HashSet<String>();
CollectionUtils.addAll(setFruit, arrayFruit);

[다운로드] https://commons.apache.org/proper/commons-collections/download_collections.cgi