TreeMap是Java Collection Framework的一個類,它實作了NavigableMap介面。它將地圖的元素儲存在樹狀結構中,並提供了一種有效的方法來按排序順序儲存鍵值對。換句話說,它總是以升序返回元素。然而,Java提供了幾種以降序遍歷TreeMap的方法。在本文中,我們將探討以逆序遍歷TreeMap的方法。
我們將使用以下方法以相反的順序列印TreeMap的元素:
範例 1
import java.util.*; public class Example1 { public static void main(String[] args) { // creating a TreeMap TreeMap<String, Integer> 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<String, Integer> 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)); } } }
Elements of the map in Reverse Order: Item: Watch, Price: 2000 Item: Pen drive, Price: 2500 Item: Keypad, Price: 1500 Item: Desktop, Price: 3000 Item: Backpack, Price: 4000
範例2
import java.util.*; public class Example2 { public static void main(String[] args) { // creating a TreeMap TreeMap<Integer, String> TrMap = new TreeMap<>(); // Adding elements in the map TrMap.put(40, "Backpack"); TrMap.put(12, "Desktop"); TrMap.put(150, "Keypad"); TrMap.put(125, "Watch"); TrMap.put(250, "Pen drive"); // retrieving the keys in reverse order Set<Integer> keys = TrMap.descendingKeySet(); // printing the details of map System.out.println("Elements of the map in Reverse Order: "); // iterating through the map for (Integer unKey : keys) { // printing details of map in reverse order System.out.println("Item: " + TrMap.get(unKey) + ", Quantity: " + unKey); } } }
Elements of the map in Reverse Order: Item: Pen drive, Quantity: 250 Item: Keypad, Quantity: 150 Item: Watch, Quantity: 125 Item: Backpack, Quantity: 40 Item: Desktop, Quantity: 12
範例3
import java.util.*; public class Example3 { public static void main(String[] args) { // creating a TreeMap by passing Collections.reverseOrder() TreeMap<String, Integer> TrMap = new TreeMap<>(Collections.reverseOrder()); // Adding elements in the map TrMap.put("Kurti", 4000); TrMap.put("Shirt", 3000); TrMap.put("TShirt", 1500); TrMap.put("Watch", 2000); TrMap.put("Perfume", 2500); // printing the details of map System.out.println("Elements of the map in Reverse Order: "); // iterating through the map for (String unKey : TrMap.keySet()) { // printing details of map in reverse order System.out.println("Item: " + unKey + ", Price: " + TrMap.get(unKey)); } } }
Elements of the map in Reverse Order: Item: Watch, Price: 2000 Item: TShirt, Price: 1500 Item: Shirt, Price: 3000 Item: Perfume, Price: 2500 Item: Kurti, Price: 4000
結論
###我們從定義TreeMap開始,在接下來的部分中,我們討論瞭如何按照相反的順序遍歷TreeMap。為了進行這個操作,我們使用了三種不同的內建方法:descendingMap(),descendingKeySet()和Collections.reverseOrder() ###以上是在Java中以相反順序迭代TreeMap的詳細內容。更多資訊請關注PHP中文網其他相關文章!