📜  Java的TreeSetDescendingIterator()方法与示例

📅  最后修改于: 2021-05-20 08:53:31             🧑  作者: Mango

Java.util.TreeSet 类的DescendingIterator ()方法用于按降序返回此集合中元素的迭代器。

句法:

public Iterator descendingIterator()

返回值:该方法以降序返回此集合中元素的迭代器。

以下示例说明了DescendingIterator()方法

范例1:

// Java program to demonstrate
// descendingIterator() method
// for Integer value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
  
            // create tree set object
            TreeSet treeadd = new TreeSet();
  
            // populate the TreeSet using add() method
            treeadd.add(10);
            treeadd.add(20);
            treeadd.add(30);
            treeadd.add(40);
  
            // Print the TreeSet
            System.out.println("TreeSet: " + treeadd);
  
            // create descending iterator
            // using descendingIterator() method
            Iterator
                iterator = treeadd.descendingIterator();
  
            System.out.println("\nValues using DescendingIterator:");
  
            // printing the interated value
            while (iterator.hasNext()) {
                System.out.println("Value : "
                                   + iterator.next());
            }
        }
  
        catch (NullPointerException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
TreeSet: [10, 20, 30, 40]

Values using DescendingIterator:
Value : 40
Value : 30
Value : 20
Value : 10

范例2:

// Java program to demonstrate
// descendingIterator() method
// for String value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
  
            // create tree set object
            TreeSet treeadd = new TreeSet();
  
            // populate the TreeSet using add() method
            treeadd.add("A");
            treeadd.add("B");
            treeadd.add("C");
            treeadd.add("D");
  
            // Print the TreeSet
            System.out.println("TreeSet: " + treeadd);
  
            // create descending iterator
            // using descendingIterator() method
            Iterator
                iterator = treeadd.descendingIterator();
  
            System.out.println("\nValues using DescendingIterator:");
  
            // printing the interated value
            while (iterator.hasNext()) {
                System.out.println("Value : "
                                   + iterator.next());
            }
        }
  
        catch (Exception e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
TreeSet: [A, B, C, D]

Values using DescendingIterator:
Value : D
Value : C
Value : B
Value : A