📜  Java中的 LinkedHashSet 示例

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

Java中的 LinkedHashSet 示例

LinkedHashSet是 HashSet 的有序版本,它在所有元素中维护一个双向链表。当需要维护迭代顺序时,使用此类。当遍历 HashSet 时,顺序是不可预测的,而 LinkedHashSet 允许我们按照元素插入的顺序遍历元素。当使用迭代器循环通过 LinkedHashSet 时,元素将按照它们被插入的顺序返回。

LinkedHashSet 的层次结构如下:

Java 中的 LinkedHashSet 示例

参数:此集合维护的元素类型

All Implemented Interfaces are as listed below:
Serializable
Cloneable,
Iterable
Collection
Set

语法:声明

public class LinkedHashSet extends HashSet implements Set, Cloneable, Serializable
  • 仅包含唯一元素,例如 HashSet。它扩展了 HashSet 类并实现了 Set 接口。
  • 维护插入顺序。

LinkedHashSet 类的构造函数

1、LinkedHashSet():这个构造函数用来创建一个默认的HashSet

LinkedHashSet hs = new LinkedHashSet();

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

LinkedHashSet hs = new LinkedHashSet(Collection c);

3、LinkedHashSet(int size):用于初始化LinkedHashSet的大小,参数中提到的整数。

LinkedHashSet hs = new LinkedHashSet(int size);

4. LinkedHashSet(int capacity, float fillRatio):可用于初始化容量和填充率,也称为LinkedHashSet的加载容量,参数中提到的参数。当元素的数量超过哈希集的容量时,乘以填充率,从而扩大了 LinkedHashSet 的容量。

LinkedHashSet hs = new LinkedHashSet(int capacity, int fillRatio);

例子:

Java
// Java Program to Illustrate LinkedHashSet
 
// Importing required classes
import java.util.LinkedHashSet;
 
// Main class
// LinkedHashSetExample
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty LinkedHashSet of string type
        LinkedHashSet linkedset
            = new LinkedHashSet();
 
        // Adding element to LinkedHashSet
        // using add() method
        linkedset.add("A");
        linkedset.add("B");
        linkedset.add("C");
        linkedset.add("D");
 
        // Note: This will not add new element
        // as A already exists
        linkedset.add("A");
        linkedset.add("E");
 
        // Getting size of LinkedHashSet
        // using size() method
        System.out.println("Size of LinkedHashSet = "
                           + linkedset.size());
 
        System.out.println("Original LinkedHashSet:"
                           + linkedset);
 
        // Removing existing entry from above Set
        // using remove() method
        System.out.println("Removing D from LinkedHashSet: "
                           + linkedset.remove("D"));
 
        // Removing existing entry from above Set
        // that does not exist in Set
        System.out.println(
            "Trying to Remove Z which is not "
            + "present: " + linkedset.remove("Z"));
 
        // Checking for element whether it is present inside
        // Set or not using contains() method
        System.out.println("Checking if A is present="
                           + linkedset.contains("A"));
 
        // Noew lastly printing the updated LinkedHashMap
        System.out.println("Updated LinkedHashSet: "
                           + linkedset);
    }
}


Java
// Java Program to Add Elements to LinkedHashSet
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
// AddingElementsToLinkedHashSet
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty LinkedHashSet
        LinkedHashSet hs = new LinkedHashSet();
 
        // Adding elements to above Set
        // using add() method
 
        // Note: Insertion order is maintained
        hs.add("Geek");
        hs.add("For");
        hs.add("Geeks");
 
        // Printing elements of Set
        System.out.println("LinkedHashSet : " + hs);
    }
}


Java
// Java program to Remove Elements from LinkedHashSet
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
// RemoveElementsFromLinkedHashSet
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty LinekdhashSet of string type
        LinkedHashSet hs
            = new LinkedHashSet();
 
        // Adding elements to above Set
        // using add() method
        hs.add("Geek");
        hs.add("For");
        hs.add("Geeks");
        hs.add("A");
        hs.add("B");
        hs.add("Z");
 
        // Printing all above elements to the console
        System.out.println("Initial HashSet " + hs);
 
        // Removing the element from above Set
        hs.remove("B");
 
        // Again removing the element
        System.out.println("After removing element " + hs);
 
        // Returning false if the element is not present
        System.out.println(hs.remove("AC"));
    }
}


Java
// Java Program to Illustrate Iterating over LinkedHashSet
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
// IteratingLinkedHashSet
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Instantiate an object of Set
        // Since LinkedHashSet implements Set
        // Set points to LinkedHashSet
        Set hs = new LinkedHashSet();
 
        // Adding elements to above Set
        // using add() method
        hs.add("Geek");
        hs.add("For");
        hs.add("Geeks");
        hs.add("A");
        hs.add("B");
        hs.add("Z");
 
        // Iterating though the LinkedHashSet
        // using iterators
        Iterator itr = hs.iterator();
 
        while (itr.hasNext())
            System.out.print(itr.next() + ", ");
 
        // New line
        System.out.println();
 
        // Using enhanced for loop for iteration
        for (String s : hs)
            System.out.print(s + ", ");
        System.out.println();
    }
}


输出
Size of LinkedHashSet = 5
Original LinkedHashSet:[A, B, C, D, E]
Removing D from LinkedHashSet: true
Trying to Remove Z which is not present: false
Checking if A is present=true
Updated LinkedHashSet: [A, B, C, E]

对 LinkedHashSet 类执行各种操作

让我们看看如何对 LinkedHashSet 执行一些常用的操作。

操作 1:添加元素

为了向 LinkedHashSet 添加元素,我们可以使用 add() 方法。这与 HashSet 不同,因为在 HashSet 中,插入顺序不保留,而是保留在 LinkedHashSet 中。

例子:

Java

// Java Program to Add Elements to LinkedHashSet
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
// AddingElementsToLinkedHashSet
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty LinkedHashSet
        LinkedHashSet hs = new LinkedHashSet();
 
        // Adding elements to above Set
        // using add() method
 
        // Note: Insertion order is maintained
        hs.add("Geek");
        hs.add("For");
        hs.add("Geeks");
 
        // Printing elements of Set
        System.out.println("LinkedHashSet : " + hs);
    }
}
输出:
LinkedHashSet : [Geek, For, Geeks]

操作 2:移除元素

可以使用 remove() 方法从 LinkedHashSet 中删除这些值。

例子:

Java

// Java program to Remove Elements from LinkedHashSet
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
// RemoveElementsFromLinkedHashSet
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty LinekdhashSet of string type
        LinkedHashSet hs
            = new LinkedHashSet();
 
        // Adding elements to above Set
        // using add() method
        hs.add("Geek");
        hs.add("For");
        hs.add("Geeks");
        hs.add("A");
        hs.add("B");
        hs.add("Z");
 
        // Printing all above elements to the console
        System.out.println("Initial HashSet " + hs);
 
        // Removing the element from above Set
        hs.remove("B");
 
        // Again removing the element
        System.out.println("After removing element " + hs);
 
        // Returning false if the element is not present
        System.out.println(hs.remove("AC"));
    }
}
输出:
Initial HashSet [Geek, For, Geeks, A, B, Z]
After removing element [Geek, For, Geeks, A, Z]
false

操作3:遍历LinkedHashSet

使用 iterator() 方法遍历 LinkedHashSet 的元素。最著名的一种是使用增强的 for 循环。

例子:

Java

// Java Program to Illustrate Iterating over LinkedHashSet
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
// IteratingLinkedHashSet
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Instantiate an object of Set
        // Since LinkedHashSet implements Set
        // Set points to LinkedHashSet
        Set hs = new LinkedHashSet();
 
        // Adding elements to above Set
        // using add() method
        hs.add("Geek");
        hs.add("For");
        hs.add("Geeks");
        hs.add("A");
        hs.add("B");
        hs.add("Z");
 
        // Iterating though the LinkedHashSet
        // using iterators
        Iterator itr = hs.iterator();
 
        while (itr.hasNext())
            System.out.print(itr.next() + ", ");
 
        // New line
        System.out.println();
 
        // Using enhanced for loop for iteration
        for (String s : hs)
            System.out.print(s + ", ");
        System.out.println();
    }
}
输出:
Geek, For, Geeks, A, B, Z, 
Geek, For, Geeks, A, B, Z, 

LinkedHashSet 的方法

METHOD

DESCRIPTION

spliterator()Creates a late-binding and fail-fast Spliterator over the elements in this set.

在类Java.util.AbstractSet 中声明的方法

METHOD

DESCRIPTION

equals(Object o)Compares the specified object with this set for equality.
hashCode()Returns the hash code value for this set.
removeAll(Collection c)Removes from this set all of its elements that are contained in the specified collection (optional operation).

在类Java.util.AbstractCollection 中声明的方法

METHOD

DESCRIPTION

addAll​(Collection c)Adds all of the elements in the specified collection to this collection (optional operation).
containsAll​(Collection c)Returns true if this collection contains all of the elements in the specified collection.
retainAll​(Collection c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
toArray()Returns an array containing all of the elements in this collection.
toArray​(T[] a)Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
toString()Returns a string representation of this collection.

在接口Java.util.Collection 中声明的方法

METHOD

DESCRIPTION

parallelStream()Returns a possibly parallel Stream with this collection as its source.

removeIf(Predicate

E> filter)

Removes all of the elements of this collection that satisfy the given predicate.
stream()Returns a sequential Stream with this collection as its source.

在类Java.util.HashSet 中声明的方法

METHOD

DESCRIPTION

add(E e)Adds the specified element to this set if it is not already present.
clear()Removes all of the elements from this set.
clone()Returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
contains(Object o)Returns true if this set contains the specified element.
isEmpty()Returns true if this set contains no elements.
iterator()Returns an iterator over the elements in this set.
remove(Object o)Removes the specified element from this set if it is present.
size()Returns the number of elements in this set (its cardinality).

在接口Java.lang.Iterable 中声明的方法

METHOD

DESCRIPTION

forEach(Consumer

 T> action)

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

在接口Java.util.Set 中声明的方法

METHODDESCRIPTION
add(element)This method is used to add a specific element to the set. The function adds the element only if the specified element is not already present in the set else the function returns False if the element is already present in the Set.
addAll(Collection c)This method is used to append all of the elements from the mentioned collection to the existing set. The elements are added randomly without following any specific order.
clear()This method is used to remove all the elements from the set but not delete the set. The reference for the set still exists.
contains(element)This method is used to check whether a specific element is present in the Set or not.
containsAll(Collection c)This method is used to check whether the set contains all the elements present in the given collection or not. This method returns true if the set contains all the elements and returns false if any of the elements are missing.
hashCode()This method is used to get the hashCode value for this instance of the Set. It returns an integer value which is the hashCode value for this instance of the Set.
isEmpty()This method is used to check whether the set is empty or not.
iterator()This method is used to return the iterator of the set. The elements from the set are returned in random order.
remove(element)This method is used to remove the given element from the set. This method returns True if the specified element is present in the Set otherwise it returns False.
removeAll(collection) This method is used to remove all the elements from the collection which are present in the set. This method returns true if this set changed as a result of the call.
retainAll(collection)This method is used to retain all the elements from the set which are mentioned in the given collection. This method returns true if this set changed as a result of the call.
size()This method is used to get the size of the set. This returns an integer value which signifies the number of elements.
toArray()This method is used to form an array of the same elements as that of the Set.
toArray​(T[] a)Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

以下是LinkedHashMap和LinkedHashSet的区别

Categories LinkedHashMapLinkedHashSet
OperationUsd to store key-value pairs.Used to store collection of things 
DuplicatesTake unique an no duplicate keys but can takeduplicate valuesStores no duplicate element 
ImplementsHashMapHashSet
ExampleMap lhm = new LinkedHashMap();Set lhs = new LinkedhashSet();