2
Sponsored Links


Ad by Google
So we have learned how to use HashMap and Hashtable now it's time to process them, I mean, although we have already seen How many ways to iterate HashMap here. In this post, I am going to show you how to sort a map. Sometimes we required to sort a map, of course based on different requirements you may need to sort HashMap or Hashtable based on key or values. But here I will show you a simple java program to sort map based on their keys. Of course TreeMap is Sorted Map and LinkedHashMap is Ordered Map, but yes they both have high payee Map implementation regarding space.

Note: HashMap and Hashtable both are UN-Sorted and UN-Ordered Map implementation.

Java Program to Sort HashMap or Hashtable


package com.javamakeuse.poc;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;

public class HashTableExample {
 public static void main(String[] args) {

  HashMap<Character, String> learnAlphabet = new HashMap<>();

  learnAlphabet.put('C', "Cat");
  learnAlphabet.put('G', "God");
  learnAlphabet.put('B', "Ball");
  learnAlphabet.put('A', "Apple");
  learnAlphabet.put('D', "Dog");
  learnAlphabet.put('E', "Elephant");
  learnAlphabet.put('F', "Fan");

  System.out.println("UN-Sorted HashMap*****");
  System.out.println(learnAlphabet);

  // Creating TreeMap
  TreeMap<Character, String> sortedMap = new TreeMap<>(learnAlphabet);
  System.out.println("Sorted HashMap using TreeMap*****");
  System.out.println(sortedMap);

  Set<Character> keySet = learnAlphabet.keySet();
  List<Character> keyList = new ArrayList<>(keySet);

  // Sorting keys
  Collections.sort(keyList);

  System.out.println("Sorted HashMap using sorted key****");

  for (Character sortedKey : keyList) {
   System.out.println(learnAlphabet.get(sortedKey));
  }
 }
}

OUT PUT:
UN-Sorted HashMap*****
{D=Dog, E=Elephant, F=Fan, G=God, A=Apple, B=Ball, C=Cat}
Sorted HashMap using TreeMap*****
{A=Apple, B=Ball, C=Cat, D=Dog, E=Elephant, F=Fan, G=God}
Sorted HashMap using sorted key****
Apple
Ball
Cat
Dog
Elephant
Fan
God
Which one is better ArrayList or LinkedList to store 10 millions of elements? Answer
Why String is immutable? Answer
Sponsored Links

2 comments:

  1. Really good material for java

    ReplyDelete
    Replies
    1. Glad to hear that, you liked it. Keep visiting, you can also share your interview experienced with us, we will post it here.

      Delete