在 Java 中将 List 转换为 Set 的最简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1429860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:58:23  来源:igfitidea点击:

Easiest way to convert a List to a Set in Java

javacollections

提问by OHHAI

What is the easiest way to convert a Listto a Setin Java?

在 Java 中将Lista转换为 a的最简单方法是什么Set

采纳答案by sepp2k

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

回答by Spina

I agree with sepp2k, but there are some other details that might matter:

我同意 sepp2k,但还有一些其他细节可能很重要:

new HashSet<Foo>(myList);

will give you an unsorted set which doesn't have duplicates. In this case, duplication is identified using the .equals() method on your objects. This is done in combination with the .hashCode() method. (For more on equality look here)

会给你一个没有重复的未排序集合。在这种情况下,重复使用对象上的 .equals() 方法来识别。这是结合 .hashCode() 方法完成的。(有关平等的更多信息,请看这里

An alternative that gives a sorted set is:

提供排序集的另一种方法是:

new TreeSet<Foo>(myList);

This works if Foo implements Comparable. If it doesn't then you may want to use a comparator:

如果 Foo 实现了 Comparable,这会起作用。如果没有,那么您可能需要使用比较器:

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

This depends on either compareTo() (from the comparable interface) or compare() (from the comparator) to ensure uniqueness. So, if you just care about uniqueness, use the HashSet. If you're after sorting, then consider the TreeSet. (Remember: Optimize later!) If time efficiency matters use a HashSet if space efficiency matters, look at TreeSet. Note that more efficient implementations of Set and Map are available through Trove (and other locations).

这取决于 compareTo()(来自可比较接口)或 compare()(来自比较器)以确保唯一性。因此,如果您只关心唯一性,请使用 HashSet。如果您在排序之后,请考虑使用 TreeSet。(记住:稍后优化!)如果时间效率很重要,如果空间效率很重要,请使用 HashSet,看看 TreeSet。请注意,可以通过 Trove(和其他位置)获得更有效的 Set 和 Map 实现。

回答by Vitalii Fedorenko

If you use the Guavalibrary:

如果您使用番石榴库:

Set<Foo> set = Sets.newHashSet(list);

or, better:

或更好:

Set<Foo> set = ImmutableSet.copyOf(list);

回答by Sandeep Bhardwaj

Set<E> alphaSet  = new HashSet<E>(<your List>);

or complete example

或完整示例

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

回答by Ashish

I would perform a Null check before converting to set.

在转换为 set 之前,我会执行 Null 检查。

if(myList != null){
Set<Foo> foo = new HashSet<Foo>(myList);
}

回答by savanibharat

You can convert List<>to Set<>

您可以转换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);
}

回答by JimB

Using java 8 you can use stream:

使用 java 8,您可以使用流:

List<Integer> mylist = Arrays.asList(100, 101, 102);
Set<Integer> myset = mylist.stream().collect(Collectors.toSet()));

回答by akhil_mittal

There are various ways to get a Setas:

有多种方法可以获取Setas:

    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 HashSetthen we can use the other alternative to get a set (check set3).

当我们使用Collectors.toSet()它时,它会返回一个集合,并根据文档:There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned。如果我们想得到一个,HashSet那么我们可以使用另一种方法来得到一个集合(检查set3)。

回答by BERGUIGA Mohamed Amine

For Java 8 it's very easy:

对于 Java 8,这很容易:

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

回答by shabunc

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

让我们不要忘记我们相对较新的朋友,java-8流 API。如果您需要在将列表转换为集合之前对其进行预处理,最好使用以下内容:

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