.asSet (…)이 API에 있습니까?
세트를 만드는 매우 간단한 방법을 찾고 있습니다.
Arrays.asList("a", "b" ...)
생성 List<String>
비슷한 것이 Set
있습니까?
이제 Java 8을 사용하면 타사 프레임 워크없이이 작업을 수행 할 수 있습니다.
Set<String> set = Stream.of("a","b","c").collect(Collectors.toSet());
수집기를 참조하십시오 .
즐겨!
Guava를 사용하면 다음 과 같이 간단합니다.
Set<String> mySet = ImmutableSet.<String> of("a", "b");
또는 변경 가능한 세트의 경우 :
Set<String> mySet = Sets.newHashSet("a", "b")
더 많은 데이터 유형은 Guava 사용자 가이드를 참조하세요.
당신은 사용할 수 있습니다
new HashSet<String>(Arrays.asList("a","b"));
멤버가 0 개 또는 1 개인 세트의 특수한 경우 다음을 사용할 수 있습니다.
java.util.Collections.EMPTY_SET
과:
java.util.Collections.singleton("A")
다른 사람들이 말했듯이 다음을 사용하십시오.
new HashSet<String>(Arrays.asList("a","b"));
이것이 Java에 존재 하지 않는 이유 Arrays.asList
는 고정 된 크기의 목록 을 반환하기 때문입니다.
public static void main(String a[])
{
List<String> myList = Arrays.asList("a", "b");
myList.add("c");
}
보고:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
클래스 Set
내부에는 "고정 크기"의 JDK 구현이 없습니다 Arrays
. 왜 이것을 원합니까? A Set
는 중복이 없음을 보장하지만 직접 입력하는 경우 해당 기능이 필요하지 않으며 List
더 많은 메서드가 있습니다. 두 인터페이스 모두 확장 Collection
및 Iterable
.
다른 사람들이 말했듯이, 이 기능을 정말로 원한다면 구아바를 사용하십시오 -JDK에 없기 때문입니다. 이에 대한 정보는 그들의 답변 (특히 Michael Schmeißer의 답변)을 참조하십시오.
Java 9에서 유사한 기능이 팩토리 메소드를 통해 추가되었습니다.
Set<String> oneLinerSet = Set.of("a", "b", ...);
(동등한 List
것도 있습니다.)
아니요하지만 이렇게 할 수 있습니다
new HashSet<String>(Arrays.asList("a", "b", ...));
구아바 에서는 다음을 사용할 수 있습니다.
Set<String> set = Sets.newHashSet("a","b","c");
다음은 사용할 수있는 작은 방법입니다.
/**
* Utility method analogous to {@link java.util.Arrays#asList(Object[])}
*
* @param ts
* @param <T>
* @return the set of all the parameters given.
*/
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> Set<T> asSet(T... ts) {
return new HashSet<>(Arrays.asList(ts));
}
Another way to do it using Java 8 and enums would be:
Set<String> set = EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.READ);
See EnumSet.
I would recommend a performance analysis between this approach and
Set<String> set = Stream.of(StandardOpenOption.CREATE, StandardOpenOption.READ).collect(Collectors.toSet());
because if you have more than five elements the javadoc of the method states that may be performance issues as you can see in the javadoc of Set.Of(E, E...).
참고URL : https://stackoverflow.com/questions/16358796/does-asset-exist-in-any-api
'IT박스' 카테고리의 다른 글
JavaScript에서 DateTime 문자열 구문 분석 (0) | 2020.08.28 |
---|---|
JavaScript에서 DateTime 문자열 구문 분석 (0) | 2020.08.28 |
Android 용 줄 바꿈 위젯 레이아웃 (0) | 2020.08.28 |
Java에서 바이트 배열을 Base64로 어떻게 변환합니까? (0) | 2020.08.28 |
Nginx가 활성화 된 사이트에서 사이트를 선택하지 않습니까? (0) | 2020.08.28 |