簡體   English   中英

在 Java 中將 List 轉換為 Set 的最簡單方法

[英]Easiest way to convert a List to a Set in Java

在 Java 中將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 實現。

如果您使用番石榴庫:

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)

Java-8

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

使用 Guva

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

在轉換為 set 之前,我會執行 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());

讓我們不要忘記我們相對較新的朋友, 流 API。 如果您需要在將列表轉換為集合之前對其進行預處理,最好使用以下內容:

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

使用構造函數的最佳方式

Set s= new HashSet(list);

在 Java 8 中,您還可以使用流 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 )。

在 Java 10 中,您現在可以使用Set#copyOf輕松地將List<E>轉換為不可修改的Set<E>

例子:

var set = Set.copyOf(list);

請記住,這是一個無序的操作,和null元素是不允許的,因為它會拋出一個NullPointerException

如果你希望它是可修改的,那么只需將它傳遞給構造函數一個Set實現。

帶有Optional.ofNullable更具 Java 8 彈性的解決方案

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

如果您使用Eclipse 集合

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

MutableSet接口擴展了java.util.SetMutableIntSet接口沒有。 您還可以使用Sets工廠類將任何Iterable轉換為Set

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

有在Eclipse類別提供的可變工廠的更多解釋在這里

如果您想要ListImmutableSet ,您可以使用Sets工廠,如下所示:

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

注意:我是 Eclipse Collections 的提交者

請記住,從 List 轉換為 Set 會從集合中刪除重復項,因為 List 支持重復項,而 Set 在 Java 中不支持重復項。

直接轉換:將 List 轉換為 Set 的最常見和最簡單的方法

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM