java.util.TreeSet類的descendingSet()方法用於返回此集合中包含的元素的逆序視圖。降序集由該集支持,因此對該集的更改會反映在降序集中,反之亦然。如果在進行任何一個集合的迭代時修改了任何一個集合(通過迭代器自己的remove操作除外),則迭代的結果是不確定的。
返回的集合的排序與Collections.reverseOrder(comparator())等效。表達式s.descendingSet().descendingSet()返回s的視圖,該視圖與s基本等效。
用法:
public NavigableSet descendingSet()
返回值:此方法返回此集合的逆序視圖。
以下示例說明了descendingSet()方法
示例1:
// 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<String> treeadd = new TreeSet<String>();
// 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<String>
treereverse = treeadd.descendingSet();
// getting iterated view of NavigableSet
Iterator<String> iterator = treereverse.iterator();
System.out.println("\nValues using DescendingSet:");
// printing the interated 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 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<Integer> treeadd = new TreeSet<Integer>();
// 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<Integer> treereverse = treeadd.descendingSet();
// getting iterated view of NavigableSet
Iterator<Integer> iterator = treereverse.iterator();
System.out.println("\nValues using DescendingSet:");
// printing the interated 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
相關用法
- Java ConcurrentSkipListSet descendingSet()用法及代碼示例
- Java NavigableSet descendingSet()用法及代碼示例
- Java TreeSet ceiling()用法及代碼示例
- Java TreeSet higher()用法及代碼示例
- Java TreeSet floor()用法及代碼示例
- Java TreeSet descendingIterator()用法及代碼示例
- Java TreeSet add()用法及代碼示例
- Java TreeSet first()用法及代碼示例
- Java TreeSet last()用法及代碼示例
- Java TreeSet contains()用法及代碼示例
- Java TreeSet clear()用法及代碼示例
- Java TreeSet headSet()用法及代碼示例
- Java TreeSet addAll()用法及代碼示例
- Java TreeSet tailSet()用法及代碼示例
- Java TreeSet isEmpty()用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 TreeSet descendingSet() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。