|
|
Program: How to reverse sorted keys in a TreeMap?
Description: |
Below example shows how to reverse keys from TreeMap based on sorting. To reverse keys, you have to sort the
TreeMap based on user defined objects by using comparator object. You can include you own
custom sorting logic with compare method. By passing comparator object to the TreeMap, you can sort the keys based on the logic
provided inside the compare method. Once the TreeMap keys are in sorting order, you can call descendingMap() method
to reverse the Map object.
|
Code: |
package com.java2novice.treemap;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class MyReverseOrderMap {
public static void main(String a[]){
//the treemap sorts by key
TreeMap<String, String> hm = new TreeMap<String, String>(new MyCopr());
//add key-value pair to TreeMap
hm.put("java", "language");
hm.put("computer", "machine");
hm.put("india","country");
hm.put("mango","fruit");
hm.put("game","cricket");
System.out.println("TreeMap Entries:");
System.out.println(hm);
Map<String, String> rm = hm.descendingMap();
System.out.println("Reverse Map Content: ");
System.out.println(rm);
}
}
class MyCopr implements Comparator<String>{
@Override
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
}
|
|
Output: |
TreeMap Entries:
{computer=machine, game=cricket, india=country, java=language, mango=fruit}
Reverse Map Content:
{mango=fruit, java=language, india=country, game=cricket, computer=machine}
|
|
|
|
|
List Of All TreeMap Sample Programs:- Basic TreeMap Operations.
- How to iterate through TreeMap?
- How to copy Map content to another TreeMap?
- How to search a key in TreeMap?
- How to search a value in TreeMap?
- How to get all keys from TreeMap?
- How to get entry set from TreeMap?
- How to delete all elements from TreeMap?
- How to sort keys in TreeMap by using Comparator?
- How to sort keys in TreeMap by using Comparator with user define objects?
- How to get sorted sub-map from TreeMap?
- How to get first key element from TreeMap (Sorted Map)?
- How to get last key element from TreeMap (Sorted Map)?
- How to reverse sorted keys in a TreeMap?
|
|
|
doPost Vs doGet methods
doGet() method is used to get information, while doPost() method is used for posting information. doGet() requests can't send large
amount of information and is limited to 240-255 characters. However, doPost()requests passes all of its data, of unlimited length.
A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas
a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.
Never argue with a fool, onlookers may not be able to tell the difference.
-- Mark Twain
|