使用降序迭代器方法在Java中反转 TreeSet 中的元素顺序
Java.util.TreeSet
例子:
Input : TreeSet = [2, 5, 6]
Output: Reverse = [6, 5, 2]
Input : TreeSet = [a, b, c]
Output: Reverse =
句法:
public Iterator descendingIterator()
返回值:此方法以降序返回此集合中元素的迭代器。
方法:
- 创建迭代器变量并使用descendingIterator() 方法的返回值对其进行初始化。
- 使用 while 循环迭代迭代器变量。
- 在循环期间打印值。
下面是上述方法的实现:
Java
// Reversing Elements Order in TreeSet in
// Java Using the descendingIterator Method
import java.util.Iterator;
import java.util.TreeSet;
class GFG {
public static void main(String[] args)
{
// Creating TreeSet and adding value to it
TreeSet setOfNumbers
= new TreeSet();
setOfNumbers.add(2);
setOfNumbers.add(5);
setOfNumbers.add(1);
setOfNumbers.add(7);
setOfNumbers.add(4);
// Printing TreeSet Elements
System.out.println("TreeSet(setOfNumbers) : "
+ setOfNumbers);
Iterator iterator
= setOfNumbers.descendingIterator();
// Iterating TreeSet
System.out.print("TreeSet in reverse order : ");
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
输出
TreeSet(setOfNumbers) : [1, 2, 4, 5, 7]
TreeSet in reverse order : 7 5 4 2 1