创建TreeSet并向其中添加元素
TreeSet<String> tSet = new TreeSet<String>(); tSet.add("P"); tSet.add("Q"); tSet.add("R"); tSet.add("S");
现在,让我们以降序遍历元素
Iterator j = tSet.descendingIterator(); while(j.hasNext()) { System.out.println(j.next()); }
以下是按降序遍历TreeSet元素的示例
import java.util.*; public class Demo { public static void main(String args[]){ TreeSet<String> tSet = new TreeSet<String>(); tSet.add("P"); tSet.add("Q"); tSet.add("R"); tSet.add("S"); System.out.println("TreeSet elements..."); Iterator<String> i = tSet.iterator(); while(i.hasNext()){ System.out.println(i.next()); } System.out.println("TreeSet elements in Descending order..."); Iterator<String> j = tSet.descendingIterator(); while(j.hasNext()) { System.out.println(j.next()); } } }
输出结果
输出如下
TreeSet elements... P Q R S TreeSet elements in Descending order... S R Q P