Java中的 TreeSet descendingSet() 方法及示例
Java.util.TreeSet
返回的集合具有等价于 Collections.reverseOrder(comparator()) 的排序。表达式 s.descendingSet().descendingSet() 返回一个与 s 基本等价的 s 视图。
句法:
public NavigableSet descendingSet()
返回值:此方法返回此集合的逆序视图。
下面是说明descendingSet()方法的例子
示例 1:
Java
// Java program to demonstrate
// descendingSet() 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);
// getting the reverse order view of element
// using descendingSet() method
NavigableSet
treereverse = treeadd.descendingSet();
// getting iterated view of NavigableSet
Iterator iterator = treereverse.iterator();
System.out.println("\nValues using DescendingSet:");
// printing the integrated value
while (iterator.hasNext()) {
System.out.println("Value : "
+ iterator.next());
}
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Java
// Java program to demonstrate
// descendingSet() 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);
// getting the reverse order view of element
// using descendingSet() method
NavigableSet treereverse = treeadd.descendingSet();
// getting iterated view of NavigableSet
Iterator iterator = treereverse.iterator();
System.out.println("\nValues using DescendingSet:");
// printing the integrated value
while (iterator.hasNext()) {
System.out.println("Value : " + iterator.next());
}
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
TreeSet: [A, B, C, D]
Values using DescendingSet:
Value : D
Value : C
Value : B
Value : A
示例 2:
Java
// Java program to demonstrate
// descendingSet() 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);
// getting the reverse order view of element
// using descendingSet() method
NavigableSet treereverse = treeadd.descendingSet();
// getting iterated view of NavigableSet
Iterator iterator = treereverse.iterator();
System.out.println("\nValues using DescendingSet:");
// printing the integrated value
while (iterator.hasNext()) {
System.out.println("Value : " + iterator.next());
}
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
Values using DescendingSet:
Value : 40
Value : 30
Value : 20
Value : 10