Development Tip

Java에서 배열을 집합으로 변환하는 방법

yourdevel 2020. 9. 30. 11:34
반응형

Java에서 배열을 집합으로 변환하는 방법


배열을 Java의 세트로 변환하고 싶습니다. 이 작업을 수행하는 몇 가지 분명한 방법 (예 : 루프 사용)이 있지만 다음과 같이 좀 더 깔끔한 것이 좋습니다.

java.util.Arrays.asList(Object[] a);

어떤 아이디어?


이렇게 :

Set<T> mySet = new HashSet<>(Arrays.asList(someArray));

Java 9+에서 수정 불가능한 세트가 정상인 경우 :

Set<T> mySet = Set.of(someArray);

Java 10 이상에서는 배열 구성 요소 유형에서 일반 유형 매개 변수를 유추 할 수 있습니다.

var mySet = Set.of(someArray);

Set<T> mySet = new HashSet<T>();
Collections.addAll(mySet, myArray);

JDK 6 Collections.addAll (java.util.Collection, T ...) 입니다.

추가로, 배열이 기본 요소로 가득 차면 어떻게 될까요?

JDK <8의 경우 for한 번의 패스로 랩 및 추가 설정을 수행하는 명백한 루프를 작성합니다 .

JDK> = 8의 경우 매력적인 옵션은 다음과 같습니다.

Arrays.stream(intArray).boxed().collect(Collectors.toSet());

Guava사용하면 다음을 수행 할 수 있습니다.

T[] array = ...
Set<T> set = Sets.newHashSet(array);

자바 8 :

String[] strArray = {"eins", "zwei", "drei", "vier"};

Set<String> strSet = Arrays.stream(strArray).collect(Collectors.toSet());
System.out.println(strSet);
// [eins, vier, zwei, drei]

Varargs도 작동합니다!

Stream.of(T... values).collect(Collectors.toSet());

자바 8

우리는 또한 사용 옵션이 Stream있습니다. 다양한 방법으로 스트림을 얻을 수 있습니다.

Set<String> set = Stream.of("A", "B", "C", "D").collect(Collectors.toCollection(HashSet::new));
System.out.println(set);

String[] stringArray = {"A", "B", "C", "D"};
Set<String> strSet1 = Arrays.stream(stringArray).collect(Collectors.toSet());
System.out.println(strSet1);

// if you need HashSet then use below option.
Set<String> strSet2 = Arrays.stream(stringArray).collect(Collectors.toCollection(HashSet::new));
System.out.println(strSet2);

의 소스 코드는 Collectors.toSet()요소가 하나씩 추가되는 것을 보여 HashSet주지만 사양이 HashSet.

"반환 된 Set의 유형, 가변성, 직렬 성 또는 스레드 안전성에 대한 보장은 없습니다."

따라서 나중에 옵션을 사용하는 것이 좋습니다. 출력은 다음과 같습니다. [A, B, C, D] [A, B, C, D] [A, B, C, D]

불변 세트 (Java 9)

Java 9 Set.of는 제공된 요소 또는 배열에 대해 변경 불가능한 집합을 반환하는 정적 팩토리 메서드를 도입했습니다 .

@SafeVarargs
static <E> Set<E> of​(E... elements)

확인 불변의 설정 정적 공장 방법을 자세한 내용은.

불변 세트 (Java 10)

두 가지 방법으로 불변 세트를 얻을 수도 있습니다.

  1. Set.copyOf(Arrays.asList(array))
  2. Arrays.stream(array).collect(Collectors.toUnmodifiableList());

The method Collectors.toUnmodifiableList() internally makes use of Set.of introduced in Java 9. Also check this answer of mine for more.


After you do Arrays.asList(array) you can execute Set set = new HashSet(list);

Here is a sample method, you can write:

public <T> Set<T> GetSetFromArray(T[] array) {
    return new HashSet<T>(Arrays.asList(array));
}

In Eclipse Collections, the following will work:

Set<Integer> set1 = Sets.mutable.of(1, 2, 3, 4, 5);
Set<Integer> set2 = Sets.mutable.of(new Integer[]{1, 2, 3, 4, 5});
MutableSet<Integer> mutableSet = Sets.mutable.of(1, 2, 3, 4, 5);
ImmutableSet<Integer> immutableSet = Sets.immutable.of(1, 2, 3, 4, 5);

Set<Integer> unmodifiableSet = Sets.mutable.of(1, 2, 3, 4, 5).asUnmodifiable();
Set<Integer> synchronizedSet = Sets.mutable.of(1, 2, 3, 4, 5).asSynchronized();
ImmutableSet<Integer> immutableSet = Sets.mutable.of(1, 2, 3, 4, 5).toImmutable();

Note: I am a committer for Eclipse Collections


Quickly : you can do :

// Fixed-size list
List list = Arrays.asList(array);

// Growable list
list = new LinkedList(Arrays.asList(array));

// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));

and to reverse

// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);

// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);

I've written the below from the advice above - steal it... it's nice!

/**
 * Handy conversion to set
 */
public class SetUtil {
    /**
     * Convert some items to a set
     * @param items items
     * @param <T> works on any type
     * @return a hash set of the input items
     */
    public static <T> Set<T> asSet(T ... items) {
        return Stream.of(items).collect(Collectors.toSet());
    }
}

There has been a lot of great answers already, but most of them won't work with array of primitives like (int[], byte[], long[], char[], etc.)

In Java 8 and above, box the array with something like:

Integer[] boxedArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);

Then a simple stream can convert it to set:

Stream.of(boxedArr).collect(Collectors.toSet());

Sometime using some standard libraries helps a lot. Try to look at the Apache Commons Collections. In this case your problems is simply transformed to something like this

String[] keys = {"blah", "blahblah"}
Set<String> myEmptySet = new HashSet<String>();
CollectionUtils.addAll(pythonKeywordSet, keys);

And here is the CollectionsUtils javadoc


    private Map<Integer, Set<Integer>> nobreaks = new HashMap();
    nobreaks.put(1, new HashSet(Arrays.asList(new int[]{2, 4, 5})));
    System.out.println("expected size is 3: " +nobreaks.get(1).size());

the output is

    expected size is 3: 1

change it to

    nobreaks.put(1, new HashSet(Arrays.asList( 2, 4, 5 )));

the output is

    expected size is 3: 3

Use CollectionUtils or ArrayUtils from stanford-postagger-3.0.jar

import static edu.stanford.nlp.util.ArrayUtils.asSet;
or 
import static edu.stanford.nlp.util.CollectionUtils.asSet;

  ...
String [] array = {"1", "q"};
Set<String> trackIds = asSet(array);

In Java 10:

String[] strs = {"A", "B"};
Set<String> set = Set.copyOf(Arrays.asList(strs));

Set.copyOf returns an unmodifiable Set containing the elements of the given Collection.

 The given Collection must not be null, and it must not contain any null elements.


new HashSet<Object>(Arrays.asList(Object[] a));

But I think this would be more efficient:

final Set s = new HashSet<Object>();    
for (Object o : a) { s.add(o); }         

Set<T> b = new HashSet<>(Arrays.asList(requiredArray));

참고URL : https://stackoverflow.com/questions/3064423/how-to-convert-an-array-to-a-set-in-java

반응형