Java에서 목록을 세트로 변환하는 가장 쉬운 방법
가장 쉬운 변환 방법은 무엇입니까?List
에 대해서Set
자바어?
Set<Foo> foo = new HashSet<Foo>(myList);
sepp2k에 동의합니다만, 그 밖에도 몇 가지 중요한 정보가 있습니다.
new HashSet<Foo>(myList);
중복되지 않은 정렬되지 않은 세트를 제공합니다.이 경우 중복은 오브젝트에서 .equals() 메서드를 사용하여 식별됩니다.이것은 .hashCode() 메서드와 조합하여 이루어집니다.(등화에 대한 자세한 내용은 여기를 참조해 주세요.)
정렬된 세트를 제공하는 다른 방법은 다음과 같습니다.
new TreeSet<Foo>(myList);
Foo가 Comparible을 구현하면 이 기능이 작동합니다.그렇지 않으면 비교기를 사용할 수 있습니다.
Set<Foo> lSet = new TreeSet<Foo>(someComparator);
lSet.addAll(myList);
이것은 일의성을 확보하기 위해 compareTo()(비교 인터페이스의 경우) 또는 compare()(비교기의 경우) 중 하나에 의존합니다.따라서 고유성만을 중시하는 경우에는 HashSet을 사용합니다.정렬 후 TreeSet을 검토하십시오(기억:나중에 최적화!)공간 효율이 중요한 경우 시간 효율이 중요한 경우 HashSet을 사용합니다.세트 및 맵의 보다 효율적인 구현은 Trove(및 기타 위치)를 통해 이용할 수 있습니다.
Guava 라이브러리를 사용하는 경우:
Set<Foo> set = Sets.newHashSet(list);
또는 보다 나은 방법:
Set<Foo> set = ImmutableSet.copyOf(list);
Java 8을 사용하면 스트림을 사용할 수 있습니다.
List<Integer> mylist = Arrays.asList(100, 101, 102);
Set<Integer> myset = mylist.stream().collect(Collectors.toSet()));
Java - addAll
set.addAll(aList);
Java - 새 개체
new HashSet(list)
자바-8
list.stream().collect(Collectors.toSet());
구바 사용
Sets.newHashSet(list)
아파치 커먼즈
CollectionUtils.addAll(targetSet, sourceList);
자바 10
var set = Set.copyOf(list);
Set<E> alphaSet = new HashSet<E>(<your List>);
또는 완전한 예
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ListToSet
{
public static void main(String[] args)
{
List<String> alphaList = new ArrayList<String>();
alphaList.add("A");
alphaList.add("B");
alphaList.add("C");
alphaList.add("A");
alphaList.add("B");
System.out.println("List values .....");
for (String alpha : alphaList)
{
System.out.println(alpha);
}
Set<String> alphaSet = new HashSet<String>(alphaList);
System.out.println("\nSet values .....");
for (String alpha : alphaSet)
{
System.out.println(alpha);
}
}
}
설정으로 변환하기 전에 Null 체크를 수행합니다.
if(myList != null){
Set<Foo> foo = new HashSet<Foo>(myList);
}
Java 8의 경우 매우 간단합니다.
List < UserEntity > vList= new ArrayList<>();
vList= service(...);
Set<UserEntity> vSet= vList.stream().collect(Collectors.toSet());
List에서 Set으로 변환하면 List는 중복을 지원하지만 Set은 Java에서 중복을 지원하지 않으므로 중복이 컬렉션에서 제거됩니다.
직접 변환 : 목록을 세트로 변환하는 가장 일반적이고 간단한 방법
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Converting a list to set
Set<String> set = new HashSet<>(list);
Apache Commons Collections : Commons Collections API를 사용하여 목록을 세트로 변환할 수도 있습니다.
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Creating a set with the same number of members in the list
Set<String> set = new HashSet<>(4);
// Adds all of the elements in the list to the target set
CollectionUtils.addAll(set, list);
[Stream] : 다른 방법으로는 지정된 목록을 스트림으로 변환한 후 스트리밍하여 :- 를 설정하는 방법이 있습니다.
// Creating a list of strings
List<String> list = Arrays.asList("One", "Two", "Three", "Four");
// Converting to set using stream
Set<String> set = list.stream().collect(Collectors.toSet());
변환할 수 있습니다.List<>
로.Set<>
Set<T> set=new HashSet<T>();
//Added dependency -> If list is null then it will throw NullPointerExcetion.
Set<T> set;
if(list != null){
set = new HashSet<T>(list);
}
우리의 비교적 새로운 친구인 java-8 스트림 API를 잊지 말자.목록을 세트로 변환하기 전에 미리 처리해야 하는 경우 다음과 같은 방법을 사용하는 것이 좋습니다.
list.stream().<here goes some preprocessing>.collect(Collectors.toSet());
생성자를 사용하는 가장 좋은 방법
Set s= new HashSet(list);
Java 8에서는 stream api를 사용할 수도 있습니다.
Set s= list.stream().collect(Collectors.toSet());
여러 가지 방법으로 얻을 수 있습니다.Set
다음과 같이 합니다.
List<Integer> sourceList = new ArrayList();
sourceList.add(1);
sourceList.add(2);
sourceList.add(3);
sourceList.add(4);
// Using Core Java
Set<Integer> set1 = new HashSet<>(sourceList); //needs null-check if sourceList can be null.
// Java 8
Set<Integer> set2 = sourceList.stream().collect(Collectors.toSet());
Set<Integer> set3 = sourceList.stream().collect(Collectors.toCollection(HashSet::new));
//Guava
Set<Integer> set4 = Sets.newHashSet(sourceList);
// Apache commons
Set<Integer> set5 = new HashSet<>(4);
CollectionUtils.addAll(set5, sourceList);
사용할 때Collectors.toSet()
다음 문서에 따라 세트를 반환합니다.There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned
만약 우리가 그것을 얻으려면HashSet
에 또 체크하다, 하세요.set3
을 사용한 Optional.ofNullable
Set<Foo> mySet = Optional.ofNullable(myList).map(HashSet::new).orElse(null);
Java 10을 사용하면 이제 를 사용하여 를 쉽게 변환할 수 있습니다.List<E>
할 수 없다Set<E>
:
예제:
var set = Set.copyOf(list);
가 없는 이며, 「」는 「」에 해 주세요.null
요소는 허용되지 않습니다,NullPointerException
.
수 .Set
★★★★★★ 。
MutableSet<Integer> mSet = Lists.mutable.with(1, 2, 3).toSet();
MutableIntSet mIntSet = IntLists.mutable.with(1, 2, 3).toSet();
MutableSet
가 확장되다java.util.Set
whereas반은MutableIntSet
인터페이스에는 없습니다. 것도 바꿀 수 요.Iterable
a까지Set
Sets
팩토리 클래스
Set<Integer> set = Sets.mutable.withAll(List.of(1, 2, 3));
이클립스 컬렉션에서 사용할 수 있는 변이 가능한 공장에 대한 자세한 설명이 여기 있습니다.
「 」가 ImmutableSet
List
을할 수 .Sets
「 」 「 」 :
ImmutableSet<Integer> immutableSet = Sets.immutable.withAll(List.of(1, 2, 3))
주의: 저는 Eclipse Collections의 커밋입니다.
Java 1.8에서는 스트림 API를 사용하여 목록을 설정할 수 있습니다.예를 들어, 다음 코드는 목록의 집합으로의 변환을 나타냅니다.
List<String> empList = Arrays.asList("java", "python", ".net", "javaScript", "php");
Set<String> set = empList.stream().collect(Collectors.toSet());
set.forEach(value -> System.out.printf("%s ", value));
목록에 개체가 포함되어 있고 개체 집합을 만들고 싶은 경우:
List<Employee> empList = Arrays.asList(new Employee(1, 1000, "Chandra Shekhar", 6000),
new Employee(2, 1000, "Rajesh", 8000), new Employee(3, 1004, "Rahul", 9000),
new Employee(4, 1001, "Suresh", 12000), new Employee(5, 1004, "Satosh", 7000));
Set<String> set = empList.stream().map(emp -> emp.getName()).collect(Collectors.toSet());
System.out.println(set);
언급URL : https://stackoverflow.com/questions/1429860/easiest-way-to-convert-a-list-to-a-set-in-java
'programing' 카테고리의 다른 글
Vuelidate - 변환 핸들러 외부의 vuex 저장소 상태 변환 안 함 (0) | 2022.07.18 |
---|---|
Vuex 및 vuex-module-decorator에서 작동하는 정적 모듈을 로드할 수 없습니다. (0) | 2022.07.18 |
Android에서 PDF 파일을 렌더링하는 방법 (0) | 2022.07.18 |
VueJS: 동일한 파일을 선택해도 입력 파일 선택 이벤트가 발생하지 않습니다. (0) | 2022.07.18 |
Vuejs 2: 스크립트 태그 javascript 파일을 DOM에 동적으로 포함(및 실행)하려면 어떻게 해야 합니까? (0) | 2022.07.18 |