Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中将列表转换为集合的最简单方法_Java_Collections_Java 8 - Fatal编程技术网

Java中将列表转换为集合的最简单方法

Java中将列表转换为集合的最简单方法,java,collections,java-8,Java,Collections,Java 8,在Java中将列表转换为集的最简单方法是什么?Set foo=new HashSet(myList); Set<Foo> foo = new HashSet<Foo>(myList); 我同意sepp2k,但还有一些其他细节可能很重要: new HashSet<Foo>(myList); newhashset(myList); 将为您提供一个没有重复项的未排序集。在本例中,使用对象上的.equals()方法识别重复。这是结合.hashCode()方法完成

在Java中将
列表
转换为
的最简单方法是什么?

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

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

new HashSet<Foo>(myList);
newhashset(myList);
将为您提供一个没有重复项的未排序集。在本例中,使用对象上的.equals()方法识别重复。这是结合.hashCode()方法完成的。(有关平等的更多信息,请参见)

给出排序集的备选方案是:

new TreeSet<Foo>(myList);
新树集(myList);
如果Foo实现了Comparable,那么这是可行的。如果没有,则可能需要使用比较器:

Set<Foo> lSet = new TreeSet<Foo>(someComparator);
lSet.addAll(myList);
Set lSet=新树集(someComparator);
lSet.addAll(myList);
这取决于compareTo()(来自comparable接口)或compare()(来自comparator)以确保唯一性。因此,如果您只关心唯一性,请使用HashSet。如果你正在排序,那么考虑树集。(记住:以后再优化!)如果时间效率很重要,请使用哈希集如果空间效率很重要,请查看TreeSet。请注意,通过Trove(和其他位置)可以更高效地实现Set和Map。

如果您使用该库:

Set Set=Sets.newHashSet(列表);
或者更好:

Set<Foo> set = ImmutableSet.copyOf(list);
Set Set=ImmutableSet.copyOf(列表);
Set alphaSet=new HashSet();
或者完整的例子

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);
        }
    }
}
import java.util.ArrayList;
导入java.util.HashSet;
导入java.util.List;
导入java.util.Set;
公共类列表集
{
公共静态void main(字符串[]args)
{
List alphaList=new ArrayList();
字母表。添加(“A”);
字母表。添加(“B”);
字母表。添加(“C”);
字母表。添加(“A”);
字母表。添加(“B”);
System.out.println(“列表值…”);
用于(字符串alpha:alphaList)
{
系统输出打印项次(α);
}
Set alphaSet=新哈希集(alphaList);
System.out.println(“\n设置值…”);
用于(字符串alpha:alphaSet)
{
系统输出打印项次(α);
}
}
}

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

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

您可以将
列表
转换为
设置

Set Set=newhashset();
//添加了依赖项->如果列表为空,则它将抛出NullPointerExcetion。
集合;
如果(列表!=null){
set=新哈希集(列表);
}

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

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

获取
集的方法有多种:

    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);
List sourceList=new ArrayList();
增加(1);
增加(2);
增加(3);
源列表。添加(4);
//使用核心Java
Set set1=新哈希集(sourceList)//如果sourceList可以为空,则需要空检查。
//爪哇8
Set set2=sourceList.stream().collect(Collectors.toSet());
Set set3=sourceList.stream().collect(Collectors.toCollection(HashSet::new));
//番石榴
Set set4=Sets.newHashSet(sourceList);
//阿帕奇公地
Set set5=新哈希集(4);
CollectionUtils.addAll(set5,sourceList);

当我们使用
Collectors.toSet()
时,它返回一个集合,并且根据文档:
对于返回的集合的类型、可变性、可序列化性或线程安全性没有任何保证。如果我们想要获得一个
哈希集
,那么我们可以使用另一个替代方法来获得一个集(选中
set3

对于Java 8,它非常简单:

List < UserEntity > vList= new ArrayList<>(); 
vList= service(...);
Set<UserEntity> vSet= vList.stream().collect(Collectors.toSet());
ListvList=newarraylist();
vList=服务(…);
设置vSet=vList.stream().collect(Collectors.toSet());

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

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

一个更具Java 8弹性的解决方案,具有
可选功能。不可用

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

使用Java 10,您现在可以使用轻松地将
列表
转换为不可修改的

例如:

var set = Set.copyOf(list);
请记住,这是一个无序操作,
null
元素是不允许的,因为它将抛出
NullPointerException


如果您希望它是可修改的,那么只需将它传递给构造函数a
Set
实现。

使用构造函数的最佳方法

Set s= new HashSet(list);
在java 8中,还可以使用流api::

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

Java-addAll

set.addAll(aList);

Java-新对象

new HashSet(list)
Java-8

list.stream().collect(Collectors.toSet());
使用Guva

 Sets.newHashSet(list)
apachecommons

CollectionUtils.addAll(targetSet, sourceList);
Java10

var set = Set.copyOf(list);
如果您使用:

Eclipse集合中提供了更多关于可变工厂的解释

如果希望从
列表中获得
不可变表集
,可以使用
集合
工厂,如下所示:

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

注意:我是Eclipse集合的提交者

请记住,从列表到集合的转换将从集合中删除重复项,因为在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);
//创建字符串列表
List=Arrays.asList(“一”、“二”、“三”、“四”);
//将列表转换为集合
Set Set=新哈希集(列表);
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);
//创建字符串列表
List=Arrays.asList(“一”、“二”和
MutableSet<Integer> mSet = Lists.mutable.with(1, 2, 3).toSet();
MutableIntSet mIntSet = IntLists.mutable.with(1, 2, 3).toSet();
Set<Integer> set = Sets.mutable.withAll(List.of(1, 2, 3));
ImmutableSet<Integer> immutableSet = Sets.immutable.withAll(List.of(1, 2, 3))
// 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);
// 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);
// 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());