📜  如何在Java中将 ArrayList 转换为 LinkedHashSet?

📅  最后修改于: 2022-05-13 01:55:38.341000             🧑  作者: Mango

如何在Java中将 ArrayList 转换为 LinkedHashSet?

ArrayList 是一种数据结构,它克服了Java中公共数组的缺点,其中必须事先明确指定大小。数组数据结构的长度不能修改,这是由 ArrayList 数据结构处理的。这种数据结构也称为动态数组,可以根据需要增长或修改。它是Collections框架下的一个类,可以通过导入Java .util包被包含在Java程序中。

LinkedHashSet 是Java中传统 HashSet 类的增强版本,它提供了 HashSet 中缺少的附加排序功能。它保持元素插入的顺序,不像 HashSet 的顺序是不可预测的。它是使用双向链表实现的,并且可以使用迭代器进行迭代。

本文使用 4 种不同的方法将 ArrayList 转换为 LinkedHashSet,如下所示:

  1. 在 LinkedHashSet 构造函数的初始化期间将 ArrayList 作为参数传递。
  2. 使用 LinkedHashSet 类的 addAll() 方法。
  3. 在迭代 ArrayList 的所有元素时使用 LinkedHashSet 类的 add() 方法。
  4. 使用流首先将 ArrayList 转换为 Set,然后再转换为 LinkedHashSet。

方法一

使用这种方法,我们只是在初始化 LinkedHashSet 类时将 ArrayList 作为参数传递

句法

LinkedHashSet(Collection C):用于用集合C的元素初始化HashSet。

例子

Java
// java program to convert ArrayList
// to LinkedHashSet
 
// importing the utils package
import java.util.*;
 
class GFG {
 
    // defining the method
    void arrayListToLinkedHashSet()
    {
 
        // initializing the ArrayList
        ArrayList arrayList = new ArrayList<>();
 
        // adding values in the ArrayList
        arrayList.add("Geeks");
        arrayList.add("For");
        arrayList.add("Geeks");
 
        // printing the list
        System.out.println("The array list : " + arrayList);
 
        // initializing the LinkedHashSet class
        // passing the ArrayList as parameter
        LinkedHashSet linkedHashSet
            = new LinkedHashSet(arrayList);
 
        // printing the LinkedHashSet
        System.out.println("The converted "
                           + "Linked Hash Set : "
                           + linkedHashSet);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // instantiating the class
        GFG ob = new GFG();
 
        // calling the method
        ob.arrayListToLinkedHashSet();
    }
}


Java
// java program to convert ArrayList
// to LinkedHashSet
 
// importing the java.utils package
import java.util.*;
 
class GFG {
 
    // defining the method
    void arrayListToLinkedHashSet()
    {
 
        // initializing the ArrayList
        ArrayList arrayList = new ArrayList<>();
 
        // filling the ArrayList with values
        arrayList.add("Geeks");
        arrayList.add("For");
        arrayList.add("Geeks");
 
        // printing the list
        System.out.println("The Array List : " + arrayList);
 
        // initializing the LinkedHashSet
        LinkedHashSet linkedHashSet
            = new LinkedHashSet<>();
 
        // using the addAll() to
        // fill the HashSet
        linkedHashSet.addAll(arrayList);
 
        // printing the LinkedHashSet
        System.out.println("The Linked "
                           + "Hash Set : " + linkedHashSet);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // instantiating the class
        GFG ob = new GFG();
 
        // calling the method
        ob.arrayListToLinkedHashSet();
    }
}


Java
// java program to convert ArrayList
// to LinkedHashSet
 
// importing the java.utils package
import java.util.*;
 
class GFG {
 
    // defining the method
    void arrayListToHashSet()
    {
 
        // initializing the ArrayList
        ArrayList arrayList = new ArrayList<>();
 
        // filling the ArrayList with values
        arrayList.add("Geeks");
        arrayList.add("For");
        arrayList.add("Geeks");
 
        // printing the list
        System.out.println("The Array List : " + arrayList);
 
        // declaring the iterator
        Iterator itr = arrayList.iterator();
 
        // initializing the LinkedHashSet
        LinkedHashSet linkedHashSet
            = new LinkedHashSet<>();
 
        // loop to iterate through the ArrayList
        while (itr.hasNext())
 
            // using the add()
            // to fill the HashSet
            linkedHashSet.add(itr.next());
 
        // printing the LinkedHashSet
        System.out.println("The Linked Hash Set : "
                           + linkedHashSet);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // instantiating the class
        GFG ob = new GFG();
 
        // calling the method
        ob.arrayListToHashSet();
    }
}


Java
// java program to convert ArrayList
// to LinkedHashSet
 
import java.util.*;
import java.util.stream.*;
 
class GFG {
 
    // defining the method
    void arrayListToLinkedHashSet()
    {
 
        // initializing the ArrayList
        ArrayList arrayList = new ArrayList<>();
 
        // filling the ArrayList with values
        arrayList.add("Geeks");
        arrayList.add("For");
        arrayList.add("Geeks");
 
        // printing the list
        System.out.println("The Array List : " + arrayList);
 
        // creating a stream from the ArrayList
        Stream stream = arrayList.stream();
 
        // creating a set from the Stream
        // using the predefined toSet()
        // method of the Collectors class
        Set set
            = stream.collect(Collectors.toSet());
 
        // converting the Set to
        // LinkedHashSet
        LinkedHashSet linkedHashSet
            = new LinkedHashSet<>(set);
 
        // printing the LinkedHashSet
        System.out.println("The Linked Hash Set : "
                           + linkedHashSet);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // instantiating the class
        GFG ob = new GFG();
 
        // calling the method
        ob.arrayListToLinkedHashSet();
    }
}


Java
// java code to convert an ArrayList
// of custom class objects to
// LinkedHashSet
 
// importing the libraries
import java.util.*;
 
// the custom class
class Sports {
 
    // global variable name of type String
    // to hold the name of the sport
    private String name;
 
    // constructor
    public Sports(String name)
    {
 
        // initializing the name
        this.name = name;
    }
 
    // method to return the string
    public String returnString()
    {
        return name + " is a great sport";
    }
}
 
// primary class
class GFG {
 
    // declaring the method
    static void arrayListToLinkedHashSet()
    {
 
        // creating an array list of type
        // class Sports
        ArrayList listOfSports
            = new ArrayList();
 
        // adding the new instances of Sports
        // in the array list
        listOfSports.add(new Sports("Football"));
        listOfSports.add(new Sports("Basketball"));
        listOfSports.add(new Sports("Football"));
 
        // printing the list
        System.out.println("The Array List : "
                           + listOfSports);
 
        // declaring an iterator of type Sports
        // to iterate over the list
        Iterator itr = listOfSports.iterator();
 
        // iterating over the list
        while (itr.hasNext())
 
            // printing the contents
            // by calling the returnString()
            System.out.println(itr.next().returnString());
 
        // initializing the linkedhashset
        // of type Sports
        LinkedHashSet linkedHashSet
            = new LinkedHashSet(listOfSports);
 
        // printing the contents of the
        // linked hash set
        System.out.println("The Linked Hash Set : "
                           + linkedHashSet);
 
        // declaring an iterator to iterate
        // over linkedhashset
        Iterator itr1 = linkedHashSet.iterator();
 
        // iterating over the linkedhashset
        while (itr1.hasNext()) {
 
            // calling the returnString()
            // of Sports
            System.out.println(itr1.next().returnString());
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // calling the method
        arrayListToLinkedHashSet();
    }
}


输出
The array list : [Geeks, For, Geeks]
The converted Linked Hash Set : [Geeks, For]

解释:
ArrayList 包含三个条目,它们是 [Geeks, For, Geeks]。这将转换为有序集并且只包含两个值: GeeksFor。由于 Set 不允许多个相似的值。

方法二

使用这种方法,我们在初始化后使用 LinkedHashSet 类的预定义方法addAll()来填充 LinkedHashSet。

句法:

LinkedHashSet.addAll(Collection C)

参数:参数C是要添加到集合中的任何类型的集合。

返回值:如果该方法成功地将集合C的元素附加到此 Set 中,则该方法返回 true,否则返回 False。

例子

Java

// java program to convert ArrayList
// to LinkedHashSet
 
// importing the java.utils package
import java.util.*;
 
class GFG {
 
    // defining the method
    void arrayListToLinkedHashSet()
    {
 
        // initializing the ArrayList
        ArrayList arrayList = new ArrayList<>();
 
        // filling the ArrayList with values
        arrayList.add("Geeks");
        arrayList.add("For");
        arrayList.add("Geeks");
 
        // printing the list
        System.out.println("The Array List : " + arrayList);
 
        // initializing the LinkedHashSet
        LinkedHashSet linkedHashSet
            = new LinkedHashSet<>();
 
        // using the addAll() to
        // fill the HashSet
        linkedHashSet.addAll(arrayList);
 
        // printing the LinkedHashSet
        System.out.println("The Linked "
                           + "Hash Set : " + linkedHashSet);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // instantiating the class
        GFG ob = new GFG();
 
        // calling the method
        ob.arrayListToLinkedHashSet();
    }
}
输出
The Array List : [Geeks, For, Geeks]
The Linked Hash Set : [Geeks, For]

方法三

使用这种方法,我们遍历 ArrayList,并在每次迭代中使用 LinkedHashSet 类的预定义 add() 方法用值填充 LinkedHashSet。

句法:

Hash_Set.add(Object element)

参数:参数元素的类型为 LinkedHashSet,指的是要添加到 Set 中的元素。

返回值:如果该元素不存在于 LinkedHashSet 中,则该函数返回 True,否则如果该元素已存在于 LinkedHashSet 中,则该函数返回 False。

例子

Java

// java program to convert ArrayList
// to LinkedHashSet
 
// importing the java.utils package
import java.util.*;
 
class GFG {
 
    // defining the method
    void arrayListToHashSet()
    {
 
        // initializing the ArrayList
        ArrayList arrayList = new ArrayList<>();
 
        // filling the ArrayList with values
        arrayList.add("Geeks");
        arrayList.add("For");
        arrayList.add("Geeks");
 
        // printing the list
        System.out.println("The Array List : " + arrayList);
 
        // declaring the iterator
        Iterator itr = arrayList.iterator();
 
        // initializing the LinkedHashSet
        LinkedHashSet linkedHashSet
            = new LinkedHashSet<>();
 
        // loop to iterate through the ArrayList
        while (itr.hasNext())
 
            // using the add()
            // to fill the HashSet
            linkedHashSet.add(itr.next());
 
        // printing the LinkedHashSet
        System.out.println("The Linked Hash Set : "
                           + linkedHashSet);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // instantiating the class
        GFG ob = new GFG();
 
        // calling the method
        ob.arrayListToHashSet();
    }
}
输出
The Array List : [Geeks, For, Geeks]
The Linked Hash Set : [Geeks, For]

方法四

在这种方法下,我们首先将 ArrayList 转换为流,然后将其转换为 Set。这个 Set 最终被转换为 LinkedHashSet。 Stream 类仅适用于 JDK 8 或更高版本。

例子

Java

// java program to convert ArrayList
// to LinkedHashSet
 
import java.util.*;
import java.util.stream.*;
 
class GFG {
 
    // defining the method
    void arrayListToLinkedHashSet()
    {
 
        // initializing the ArrayList
        ArrayList arrayList = new ArrayList<>();
 
        // filling the ArrayList with values
        arrayList.add("Geeks");
        arrayList.add("For");
        arrayList.add("Geeks");
 
        // printing the list
        System.out.println("The Array List : " + arrayList);
 
        // creating a stream from the ArrayList
        Stream stream = arrayList.stream();
 
        // creating a set from the Stream
        // using the predefined toSet()
        // method of the Collectors class
        Set set
            = stream.collect(Collectors.toSet());
 
        // converting the Set to
        // LinkedHashSet
        LinkedHashSet linkedHashSet
            = new LinkedHashSet<>(set);
 
        // printing the LinkedHashSet
        System.out.println("The Linked Hash Set : "
                           + linkedHashSet);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // instantiating the class
        GFG ob = new GFG();
 
        // calling the method
        ob.arrayListToLinkedHashSet();
    }
}
输出
The Array List : [Geeks, For, Geeks]
The Linked Hash Set : [Geeks, For]

将自定义类对象的 ArrayList 转换为 LinkedHashSet

上面的例子说明了转换原始数据类型(如整数、字符串等)的 ArrayList 的过程。在这里,我们将使用上述方法将自定义类对象的 ArrayList 转换为 LinkedHashSet。转换的一个有趣特性是,这允许复制上述场景中不允许的对象。相同的原因是每次创建同一类的新对象时,在比较对象时,用于在将元素输入集合之前检查元素的 equals() 方法会找到唯一的引用,因为每个新对象都拥有一个新参考。这允许相同的数据出现在 LinkedHashSet 中的多个位置。

例子

Java

// java code to convert an ArrayList
// of custom class objects to
// LinkedHashSet
 
// importing the libraries
import java.util.*;
 
// the custom class
class Sports {
 
    // global variable name of type String
    // to hold the name of the sport
    private String name;
 
    // constructor
    public Sports(String name)
    {
 
        // initializing the name
        this.name = name;
    }
 
    // method to return the string
    public String returnString()
    {
        return name + " is a great sport";
    }
}
 
// primary class
class GFG {
 
    // declaring the method
    static void arrayListToLinkedHashSet()
    {
 
        // creating an array list of type
        // class Sports
        ArrayList listOfSports
            = new ArrayList();
 
        // adding the new instances of Sports
        // in the array list
        listOfSports.add(new Sports("Football"));
        listOfSports.add(new Sports("Basketball"));
        listOfSports.add(new Sports("Football"));
 
        // printing the list
        System.out.println("The Array List : "
                           + listOfSports);
 
        // declaring an iterator of type Sports
        // to iterate over the list
        Iterator itr = listOfSports.iterator();
 
        // iterating over the list
        while (itr.hasNext())
 
            // printing the contents
            // by calling the returnString()
            System.out.println(itr.next().returnString());
 
        // initializing the linkedhashset
        // of type Sports
        LinkedHashSet linkedHashSet
            = new LinkedHashSet(listOfSports);
 
        // printing the contents of the
        // linked hash set
        System.out.println("The Linked Hash Set : "
                           + linkedHashSet);
 
        // declaring an iterator to iterate
        // over linkedhashset
        Iterator itr1 = linkedHashSet.iterator();
 
        // iterating over the linkedhashset
        while (itr1.hasNext()) {
 
            // calling the returnString()
            // of Sports
            System.out.println(itr1.next().returnString());
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // calling the method
        arrayListToLinkedHashSet();
    }
}
输出
The Array List : [Sports@4e50df2e, Sports@1d81eb93, Sports@7291c18f]
Football is a great sport
Basketball is a great sport
Football is a great sport
The Linked Hash Set : [Sports@4e50df2e, Sports@1d81eb93, Sports@7291c18f]
Football is a great sport
Basketball is a great sport
Football is a great sport

解释:
在第一行,打印出 ArrayList 的内容,可以看出是对 Sports 类的引用。下面三行打印了 Sports 类的 returnString() 方法的内容。应该注意的是,所有引用都是唯一的,因此即使内容可能相同,LinkedHashSet 也允许它们。在下一行中,将打印 LinkedHashSet 的内容,这些内容再次引用类 Sports。接下来的几行是returnString()方法调用。