在Java中以相反顺序迭代TreeMap

在Java中以相反顺序迭代TreeMap

TreeMap是Java Collection Framework的一个类,它实现了NavigableMap接口。它将地图的元素存储在树结构中,并提供了一种有效的方法来按排序顺序存储键值对。换句话说,它总是以升序返回元素。然而,Java提供了几种以降序遍历TreeMap的方法。在本文中,我们将探讨以逆序遍历TreeMap的方法。

在Java中以相反顺序迭代TreeMap

我们将使用以下方法以相反的顺序打印TreeMap的元素:

  • 使用TreeMap.descendingMap()方法

  • 使用TreeMap.descendingKeySet()方法

  • 使用 Collections.reverseOrder() 方法

让我们通过示例程序逐一讨论它们

Example 1

在这个例子中,我们将使用内置的方法TreeMap.descendingMap()来以相反的顺序迭代TreeMap。为此,我们首先定义一个TreeMap,然后将其元素按相反的顺序存储到另一个map中。

import java.util.*; public class Example1 { public static void main(String[] args) { // creating a TreeMap TreeMap TrMap = new TreeMap(); // Adding elements in the map TrMap.put("Backpack", 4000); TrMap.put("Desktop", 3000); TrMap.put("Keypad", 1500); TrMap.put("Watch", 2000); TrMap.put("Pen drive", 2500); // storing the elements of the map in descending order Map newMap = TrMap.descendingMap(); // printing the details of map System.out.println("Elements of the map in Reverse Order: "); // iterating through the map for (String unKey : newMap.keySet()) { // printing details of map in reverse order System.out.println("Item: " + unKey + ", Price: " + newMap.get(unKey)); } } } 登录后复制