Programing

Java에서 목록을 집합으로 변환하는 가장 쉬운 방법

lottogame 2020. 10. 3. 09:48
반응형

Java에서 목록을 집합으로 변환하는 가장 쉬운 방법


Java에서 a List로 변환하는 가장 쉬운 방법은 무엇입니까 Set?


Set<Foo> foo = new HashSet<Foo>(myList);

나는 sepp2k에 동의하지만 중요한 다른 세부 사항이 있습니다.

new HashSet<Foo>(myList);

중복이없는 정렬되지 않은 세트를 제공합니다. 이 경우 중복은 객체에서 .equals () 메서드를 사용하여 식별됩니다. 이는 .hashCode () 메서드와 함께 수행됩니다. (평등에 대한 자세한 내용은 여기 를 참조 하십시오 )

정렬 된 세트를 제공하는 대안은 다음과 같습니다.

new TreeSet<Foo>(myList);

Foo가 Comparable을 구현하면 작동합니다. 그렇지 않은 경우 비교기를 사용할 수 있습니다.

Set<Foo> lSet = new TreeSet<Foo>(someComparator);
lSet.addAll(myList);

이것은 고유성을 보장하기 위해 compareTo () (비교 인터페이스에서) 또는 compare () (비교기에서)에 따라 다릅니다. 따라서 고유성에만 관심이 있다면 HashSet을 사용하십시오. 정렬 후라면 TreeSet을 고려하십시오. (기억하십시오 : 나중에 최적화하십시오!) 시간 효율성이 중요한 경우 공간 효율성이 중요한 경우 HashSet을 사용하십시오. TreeSet을 살펴보십시오. Trove (및 기타 위치)를 통해보다 효율적인 Set 및 Map 구현을 사용할 수 있습니다.


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()));

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);
}

다음으로 변환 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의 경우 매우 쉽습니다.

List < UserEntity > vList= new ArrayList<>(); 
vList= service(...);
Set<UserEntity> vSet= vList.stream().collect(Collectors.toSet());

Let's not forget our relatively new friend, stream API. If you need to preprocess list before converting it to a set, it's better to have something like:

list.stream().<here goes some preprocessing>.collect(Collectors.toSet());

Java- addAll

set.addAll(aList);

Java- new Object

new HashSet(list)

Java-8

list.stream().collect(Collectors.toSet());

Using Guva

 Sets.newHashSet(list)

Apache Commons

CollectionUtils.addAll(targetSet, sourceList);

There are various ways to get a Set as:

    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);

When we use Collectors.toSet() it returns a set and as per the doc:There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned. If we want to get a HashSet then we can use the other alternative to get a set (check set3).


With Java 10, you could now use Set#copyOf to easily convert a List<E> to an unmodifiable Set<E>:

Example:

var set = Set.copyOf(list);

Keep in mind that this is an unordered operation, and null elements are not permitted, as it will throw a NullPointerException.

If you wish for it to be modifiable, then simply pass it into the constructor a Set implementation.


A more Java 8 resilient solution with Optional.ofNullable

Set<Foo> mySet = Optional.ofNullable(myList).map(HashSet::new).orElse(null);

The best way to use constructor

Set s= new HashSet(list);

In java 8 you can also use stream api::

Set s= list.stream().collect(Collectors.toSet());

If you use Eclipse Collections:

MutableSet<Integer> mSet = Lists.mutable.with(1, 2, 3).toSet();
MutableIntSet mIntSet = IntLists.mutable.with(1, 2, 3).toSet();

The MutableSet interface extends java.util.Set whereas the MutableIntSet interface does not. You can also convert any Iterable to a Set using the Sets factory class.

Set<Integer> set = Sets.mutable.withAll(List.of(1, 2, 3));

There is more explanation of the mutable factories available in Eclipse Collections here.

If you want an ImmutableSet from a List, you can use the Sets factory as follows:

ImmutableSet<Integer> immutableSet = Sets.immutable.withAll(List.of(1, 2, 3))

Note: I am a committer for Eclipse Collections

참고URL : https://stackoverflow.com/questions/1429860/easiest-way-to-convert-a-list-to-a-set-in-java

반응형