Checkout for Promo Codes

Program: How to sort keys in TreeMap by using Comparator?


Below example shows how to use Comparator with TreeMap. Comarator is required to implement your own sorting logic. You have to provide the sorting logic inside compare methods. Comparator is very much useful if you are working with user defined objects.

package com.java2novice.treemap;

import java.util.Comparator;
import java.util.TreeMap;

public class MyTreeMapComparator {
	public static void main(String a[]){
		//the treemap sorts by key
		TreeMap<String, String> hm = new TreeMap<String, String>(new MyComp());
		//add key-value pair to TreeMap
		hm.put("java", "language");
		hm.put("computer", "machine");

class MyComp implements Comparator<String>{

	public int compare(String str1, String str2) {
		return str1.compareTo(str2);

{computer=machine, india=country, java=language, mango=fruit}
<< Previous Program | Next Program >>

List Of All TreeMap Sample Programs:

  1. Basic TreeMap Operations.
  2. How to iterate through TreeMap?
  3. How to copy Map content to another TreeMap?
  4. How to search a key in TreeMap?
  5. How to search a value in TreeMap?
  6. How to get all keys from TreeMap?
  7. How to get entry set from TreeMap?
  8. How to delete all elements from TreeMap?
  9. How to sort keys in TreeMap by using Comparator?
  10. How to sort keys in TreeMap by using Comparator with user define objects?
  11. How to get sorted sub-map from TreeMap?
  12. How to get first key element from TreeMap (Sorted Map)?
  13. How to get last key element from TreeMap (Sorted Map)?
  14. How to reverse sorted keys in a TreeMap?
Knowledge Centre
What is daemon thread?
Daemon thread is a low priority thread. It runs intermittently in the back ground, and takes care of the garbage collection operation for the java runtime system. By calling setDaemon() method is used to create a daemon thread.
Famous Quotations
Success consists of going from failure to failure without loss of enthusiasm.
-- Winston Churchill

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2020 by Nataraja Gootooru. All Rights Reserved.