📜  Java中的 NavigableSet 和示例

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

Java中的 NavigableSet 和示例

NavigableSet 表示Java Collection Framework 中的可导航集。 NavigableSet 接口继承自 SortedSet 接口。它的行为类似于 SortedSet,但除了 SortedSet 的排序机制之外,我们还有可用的导航方法。
例如,与 SortedSet 中定义的顺序相比,NavigableSet 接口可以以相反的顺序导航集合。可以按升序或降序访问和遍历 NavigableSet。实现此接口的类是 TreeSet 和 ConcurrentSkipListSet

Java 中的 NavigableSet 和示例

这里,E 是这个集合维护的元素的类型。

所有超接口:

集合、可迭代、集合、排序集

所有已知的实现类:

ConcurrentSkipListSet, TreeSet

声明: NavigableSet 声明为

创建 NavigableSet 对象

由于 NavigableSet 是一个接口,因此无法创建 NavigableSet 类型的对象。我们总是需要一个扩展这个列表的类来创建一个对象。而且,在Java 1.5 中引入泛型之后,可以限制 NavigableSet 中可以存储的对象类型。这个类型安全的集合可以定义为:

例子:

Java
// Java program to demonstrate
// the working of NavigableSet
import java.util.NavigableSet;
import java.util.TreeSet;
 
public class NavigableSetDemo
{
    public static void main(String[] args)
    {
        NavigableSet ns = new TreeSet<>();
        ns.add(0);
        ns.add(1);
        ns.add(2);
        ns.add(3);
        ns.add(4);
        ns.add(5);
        ns.add(6);
 
        // Get a reverse view of the navigable set
        NavigableSet reverseNs = ns.descendingSet();
 
        // Print the normal and reverse views
        System.out.println("Normal order: " + ns);
        System.out.println("Reverse order: " + reverseNs);
 
        NavigableSet threeOrMore = ns.tailSet(3, true);
        System.out.println("3 or  more:  " + threeOrMore);
        System.out.println("lower(3): " + ns.lower(3));
        System.out.println("floor(3): " + ns.floor(3));
        System.out.println("higher(3): " + ns.higher(3));
        System.out.println("ceiling(3): " + ns.ceiling(3));
 
        System.out.println("pollFirst(): " + ns.pollFirst());
        System.out.println("Navigable Set:  " + ns);
 
        System.out.println("pollLast(): " + ns.pollLast());
        System.out.println("Navigable Set:  " + ns);
 
        System.out.println("pollFirst(): " + ns.pollFirst());
        System.out.println("Navigable Set:  " + ns);
 
        System.out.println("pollFirst(): " + ns.pollFirst());
        System.out.println("Navigable Set:  " + ns);
 
        System.out.println("pollFirst(): " + ns.pollFirst());
        System.out.println("Navigable Set:  " + ns);
 
        System.out.println("pollFirst(): " + ns.pollFirst());
        System.out.println("pollLast(): " + ns.pollLast());
    }
}


Java
// Java code to demonstrate
// adding of elements in
// NavigableSet
import java.util.*;
import java.io.*;
 
class NavigableSetDemo {
 
    public static void main(String[] args)
    {
        NavigableSet ts = new TreeSet();
 
        // Elements are added using add() method
        ts.add("A");
        ts.add("B");
        ts.add("C");
        ts.add("A");
 
        System.out.println(ts);
    }
}


Java
// Java program to access
// the elements of NavigableSet
import java.util.*;
import java.io.*;
 
class NavigableSetDemo {
 
    public static void main(String[] args)
    {
        NavigableSet ts = new TreeSet();
 
        // Elements are added using add() method
        ts.add("A");
        ts.add("B");
        ts.add("C");
        ts.add("A");
 
        System.out.println("Navigable Set is " + ts);
 
        String check = "D";
 
        // Check if the above string exists in
        // the NavigableSet or not
        System.out.println("Contains " + check + " "
                           + ts.contains(check));
 
        // Print the first element in
        // the NavigableSet
        System.out.println("First Value " + ts.first());
 
        // Print the last element in
        // the NavigableSet
        System.out.println("Last Value " + ts.last());
    }
}


Java
// Java Program to remove the
// elements from NavigableSet
import java.util.*;
import java.io.*;
 
class NavigableSetDemo {
 
    public static void main(String[] args)
    {
        NavigableSet ts = new TreeSet();
 
        // Elements are added using add() method
        ts.add("A");
        ts.add("B");
        ts.add("C");
        ts.add("B");
        ts.add("D");
        ts.add("E");
 
        System.out.println("Initial TreeSet " + ts);
 
        // Removing the element b
        ts.remove("B");
 
        System.out.println("After removing element " + ts);
 
        // Remove the First element of TreeSet
        ts.pollFirst();
 
        System.out.println(
            "After the removal of First Element " + ts);
 
        // Remove the Last element of TreeSet
        ts.pollLast();
 
        System.out.println(
            "After the removal of Last Element " + ts);
    }
}


Java
// Java program to iterate
// through NavigableSet
 
import java.util.*;
import java.io.*;
 
class NavigableSetDemo {
   
    public static void main(String[] args)
    {
        NavigableSet ts = new TreeSet();
 
        // Elements are added using add() method
        ts.add("C");
        ts.add("D");
        ts.add("E");
        ts.add("A");
        ts.add("B");
        ts.add("Z");
 
        // Iterating though the NavigableSet
        for (String value : ts)
            System.out.print(value + ", ");
        System.out.println();
    }
}


输出
Normal order: [0, 1, 2, 3, 4, 5, 6]
Reverse order: [6, 5, 4, 3, 2, 1, 0]
3 or  more:  [3, 4, 5, 6]
lower(3): 2
floor(3): 3
higher(3): 4
ceiling(3): 3
pollFirst(): 0
Navigable Set:  [1, 2, 3, 4, 5, 6]
pollLast(): 6
Navigable Set:  [1, 2, 3, 4, 5]
pollFirst(): 1
Navigable Set:  [2, 3, 4, 5]
pollFirst(): 2
Navigable Set:  [3, 4, 5]
pollFirst(): 3
Navigable Set:  [4, 5]
pollFirst(): 4
pollLast(): 5


对 NavigableSet 执行各种操作

由于 NavigableSet 是一个接口,它只能与实现该接口的类一起使用。 TreeSet 是实现 NavigableSet 接口的类。现在,让我们看看如何对 TreeSet 执行一些常用的操作。

1. 添加元素:为了向 NavigableSet 添加元素,我们可以使用 add() 方法。但是,插入顺序不会保留在 TreeSet 中。在内部,对于每个元素,值都会按升序进行比较和排序。我们需要注意,不允许重复元素,所有重复元素都将被忽略。而且,NavigableSet 不接受 Null 值。

Java

// Java code to demonstrate
// adding of elements in
// NavigableSet
import java.util.*;
import java.io.*;
 
class NavigableSetDemo {
 
    public static void main(String[] args)
    {
        NavigableSet ts = new TreeSet();
 
        // Elements are added using add() method
        ts.add("A");
        ts.add("B");
        ts.add("C");
        ts.add("A");
 
        System.out.println(ts);
    }
}

输出:

[A, B, C]


2. 访问元素:添加元素后,如果我们想访问元素,我们可以使用内置方法,如 contains()、first()、last() 等。

  • 包含()
  • 第一的()
  • 最后的()

Java

// Java program to access
// the elements of NavigableSet
import java.util.*;
import java.io.*;
 
class NavigableSetDemo {
 
    public static void main(String[] args)
    {
        NavigableSet ts = new TreeSet();
 
        // Elements are added using add() method
        ts.add("A");
        ts.add("B");
        ts.add("C");
        ts.add("A");
 
        System.out.println("Navigable Set is " + ts);
 
        String check = "D";
 
        // Check if the above string exists in
        // the NavigableSet or not
        System.out.println("Contains " + check + " "
                           + ts.contains(check));
 
        // Print the first element in
        // the NavigableSet
        System.out.println("First Value " + ts.first());
 
        // Print the last element in
        // the NavigableSet
        System.out.println("Last Value " + ts.last());
    }
}

输出:

Navigable Set is [A, B, C]
Contains D false
First Value A
Last Value C


3. 删除值:可以使用 remove()、pollFirst()、pollLast() 方法从 NavigableSet 中删除值。

  • 消除()
  • 民意调查()
  • 民意调查()

Java

// Java Program to remove the
// elements from NavigableSet
import java.util.*;
import java.io.*;
 
class NavigableSetDemo {
 
    public static void main(String[] args)
    {
        NavigableSet ts = new TreeSet();
 
        // Elements are added using add() method
        ts.add("A");
        ts.add("B");
        ts.add("C");
        ts.add("B");
        ts.add("D");
        ts.add("E");
 
        System.out.println("Initial TreeSet " + ts);
 
        // Removing the element b
        ts.remove("B");
 
        System.out.println("After removing element " + ts);
 
        // Remove the First element of TreeSet
        ts.pollFirst();
 
        System.out.println(
            "After the removal of First Element " + ts);
 
        // Remove the Last element of TreeSet
        ts.pollLast();
 
        System.out.println(
            "After the removal of Last Element " + ts);
    }
}

输出:

Initial TreeSet [A, B, C, D, E]
After removing element [A, C, D, E]
After the removal of First Element [C, D, E]
After the removal of Last Element [C, D]


4. 遍历 NavigableSet:有多种方法可以遍历 NavigableSet。最著名的一种是使用增强的 for 循环。

Java

// Java program to iterate
// through NavigableSet
 
import java.util.*;
import java.io.*;
 
class NavigableSetDemo {
   
    public static void main(String[] args)
    {
        NavigableSet ts = new TreeSet();
 
        // Elements are added using add() method
        ts.add("C");
        ts.add("D");
        ts.add("E");
        ts.add("A");
        ts.add("B");
        ts.add("Z");
 
        // Iterating though the NavigableSet
        for (String value : ts)
            System.out.print(value + ", ");
        System.out.println();
    }
}

输出:

A, B, C, D, E, Z,  


可导航集的方法

以下是 NavigableSet 接口中存在的方法。

METHOD

DESCRIPTION

 ceiling​(E e)Returns the least element in this set greater than or equal to the given element, or null if there is no such element.
descendingIterator()Returns an iterator over the elements in this set, in descending order.
descendingSet()Returns a reverse order view of the elements contained in this set.
floor​(E e)Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
headSet​(E toElement)Returns a view of the portion of this set whose elements are strictly less than toElement.
headSet​(E toElement, boolean inclusive)Returns a view of the portion of this set whose elements are less than (or equal to, if inclusive is true) toElement.
higher​(E e)Returns the least element in this set strictly greater than the given element, or null if there is no such element.
iterator()Returns an iterator over the elements in this set, in ascending order.
lower​(E e)Returns the greatest element in this set strictly less than the given element, or null if there is no such element.
pollFirst()Retrieves and removes the first (lowest) element, or returns null if this set is empty.
pollLast()Retrieves and removes the last (highest) element, or returns null if this set is empty.

subSet​(E fromElement, boolean

fromInclusive, E toElement, boolean toInclusive)

Returns a view of the portion of this set whose elements range from fromElement to toElement.
subSet​(E fromElement, E toElement)Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
tailSet​(E fromElement)Returns a view of the portion of this set whose elements are greater than or equal to fromElement.
tailSet​(E fromElement, boolean inclusive)Returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.


从接口Java.util.SortedSet 继承的方法

METHOD

DESCRIPTION

comparator() This method returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.
first()This method returns the first(lowest) element present in this set.
last()This method returns the last(highest) element present in the set.
spliterator()Creates a Spliterator over the elements in this sorted set.

从接口Java.util.Set 继承的方法

METHOD

DESCRIPTION

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

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.

equals()Compares the specified object with this set for equality.
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 if a NavigableSet is empty or not.
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.

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

METHODDESCRIPTION
parallelStream()Returns a possibly parallel Stream with this collection as its source.
removeIf​(Predicate 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.
toArray​(IntFunction generator)Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

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

METHODDESCRIPTION
forEach​(Consumer action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.