• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

How to Sort HashMap in Java by Values

September 29, 2015 by javainterviewpoint Leave a Comment

In my previous post we have learnt How to Sort HashMap in Java by Keys, in this article we will learn to sort HashMap values. We will be using the below three approaches.

  1. Implementing the Comparator Interface along with TreeMap Collection
  2. Implementing a separate class implementing Comparator Interface
  3. Using Collections.sort() method

1. HashMap Sorting by Values Example – Using TreeMap and Comparator

In this example we will sort the values of the HashMap using TreeMap and Comparator. We will be passing the keys to the comparator through which we can get the Value and sort the values.

package com.javainterviewpoint.HashMap;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SortByValuesHashMapExample 
{
    public static void main(String[] args) {
        
        final Map<Integer, String> unsortedMap = new HashMap<Integer, String>();
        unsortedMap.put(5, "asd");
        unsortedMap.put(1, "cfd");
        unsortedMap.put(7, "gdf");
        unsortedMap.put(55, "qwe");
        unsortedMap.put(66, "weq");
        unsortedMap.put(3, "wer");
        unsortedMap.put(8, "yes");
        unsortedMap.put(93, "nsa");
        unsortedMap.put(50, "tes");
        unsortedMap.put(12, "mds");
        unsortedMap.put(43, "fsa");
        
        //Print the Elements of the Map before Sorting
        System.out.println("Elements of the HashMap before Sorting");
        printMap(unsortedMap);
        
        Map<Integer,String> sortedMap = 
                new TreeMap<Integer,String>(new Comparator()
        {
            @Override
            public int compare(Integer i1, Integer i2)
            {
                return unsortedMap.get(i1).compareTo(unsortedMap.get(i2));
            }
        }
                );
        
        sortedMap.putAll(unsortedMap);
        //Print the Elements of the Map after Sorting
        System.out.println("Elements of the HashMap after Sorting");
        printMap(sortedMap);
        
    }

    public static void printMap(Map<Integer, String> map) {
        System.out.println("**************************************");
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() 
                                      + " Value : " + entry.getValue());
        }
        System.out.println();
    }
}

Output :

Elements of the HashMap before Sorting
**************************************
Key : 50 Value : tes
Key : 1 Value : cfd
Key : 3 Value : wer
Key : 55 Value : qwe
Key : 5 Value : asd
Key : 66 Value : weq
Key : 7 Value : gdf
Key : 93 Value : nsa
Key : 8 Value : yes
Key : 43 Value : fsa
Key : 12 Value : mds

Elements of the HashMap after Sorting
**************************************
Key : 5 Value : asd
Key : 1 Value : cfd
Key : 43 Value : fsa
Key : 7 Value : gdf
Key : 12 Value : mds
Key : 93 Value : nsa
Key : 55 Value : qwe
Key : 50 Value : tes
Key : 66 Value : weq
Key : 3 Value : wer
Key : 8 Value : yes

2. HashMap Sorting by Values Example – Separate Comparator class

Here we will be implementing the comparator interface to a separate class called ValueComparator and we will be passing it to the TreeMap.

package com.javainterviewpoint.HashMap;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SortByValuesHashMapExample 
{
    public static void main(String[] args) {
        
        Map<Integer, String> unsortedMap = new HashMap<Integer, String>();
        unsortedMap.put(5, "asd");
        unsortedMap.put(1, "cfd");
        unsortedMap.put(7, "gdf");
        unsortedMap.put(55, "qwe");
        unsortedMap.put(66, "weq");
        unsortedMap.put(3, "wer");
        unsortedMap.put(8, "yes");
        unsortedMap.put(93, "nsa");
        unsortedMap.put(50, "tes");
        unsortedMap.put(12, "mds");
        unsortedMap.put(43, "fsa");
        
        //Print the Elements of the Map before Sorting
        System.out.println("Elements of the HashMap before Sorting");
        printMap(unsortedMap);
        
        Map<Integer,String> sortedMap = 
                new TreeMap<Integer,String>(new ValueComparator(unsortedMap));
        
        sortedMap.putAll(unsortedMap);
        //Print the Elements of the Map after Sorting
        System.out.println("Elements of the HashMap after Sorting");
        printMap(sortedMap);
        
    }

    public static void printMap(Map<Integer, String> map) {
        System.out.println("**************************************");
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() 
                                      + " Value : " + entry.getValue());
        }
        System.out.println();
    }
}
class ValueComparator implements Comparator
{
    Map<Integer,String> unsortedMap;
    
    public ValueComparator(Map unsortedMap) {
        this.unsortedMap = unsortedMap;
    }
    
    @Override
    public int compare(Integer i1,Integer i2)
    {
        return unsortedMap.get(i1).compareTo(unsortedMap.get(i2));
    }
}

Output :

Elements of the HashMap before Sorting
**************************************
Key : 50 Value : tes
Key : 1 Value : cfd
Key : 3 Value : wer
Key : 55 Value : qwe
Key : 5 Value : asd
Key : 66 Value : weq
Key : 7 Value : gdf
Key : 93 Value : nsa
Key : 8 Value : yes
Key : 43 Value : fsa
Key : 12 Value : mds

Elements of the HashMap after Sorting
**************************************
Key : 5 Value : asd
Key : 1 Value : cfd
Key : 43 Value : fsa
Key : 7 Value : gdf
Key : 12 Value : mds
Key : 93 Value : nsa
Key : 55 Value : qwe
Key : 50 Value : tes
Key : 66 Value : weq
Key : 3 Value : wer
Key : 8 Value : yes

3. HashMap Sorting by Values Example – Collections.sort() method

In this approach we will be getting the EntrySet and store it to a List(unsortedList)and pass the list along with the comparator to Collections.sort() method. Finally add the sortedList to the LinkedHashMap(sortedMap) as it will maintain the insertion order.

package com.javainterviewpoint.HashMap;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortByValuesHashMapExample
{
    public static void main(String[] args) {
        
        final Map<Integer, String> unsortedMap = new HashMap<Integer, String>();
        unsortedMap.put(5, "asd");
        unsortedMap.put(1, "cfd");
        unsortedMap.put(7, "gdf");
        unsortedMap.put(55, "qwe");
        unsortedMap.put(66, "weq");
        unsortedMap.put(3, "wer");
        unsortedMap.put(8, "yes");
        unsortedMap.put(93, "nsa");
        unsortedMap.put(50, "tes");
        unsortedMap.put(12, "mds");
        unsortedMap.put(43, "fsa");
        
        //Print the Elements of the Map before Sorting
        System.out.println("Elements of the HashMap before Sorting");
        printMap(unsortedMap);
        
        List<Entry<Integer,String>> unsortedList = new ArrayList<Entry<Integer,String>>(unsortedMap.entrySet());
        Collections.sort(unsortedList,new Comparator<Entry<Integer,String>>()
                {
                    @Override
                    public int compare(Entry<Integer,String> e1, Entry<Integer,String> e2)
                    {
                        return e1.getValue().compareTo(e2.getValue());
                    }
                });
        Map<Integer,String> sortedMap = new LinkedHashMap<Integer,String>();
            
        for(Entry<Integer,String> entry:unsortedList){
            sortedMap.put(entry.getKey(),entry.getValue());
        }
        //Print the Elements of the Map after Sorting
        System.out.println("Elements of the HashMap after Sorting");
        printMap(sortedMap);
        
    }

    public static void printMap(Map<Integer, String> map) {
        System.out.println("**************************************");
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() 
                                      + " Value : " + entry.getValue());
        }
        System.out.println();
    }
}

Output :

Elements of the HashMap before Sorting
**************************************
Key : 50 Value : tes
Key : 1 Value : cfd
Key : 3 Value : wer
Key : 55 Value : qwe
Key : 5 Value : asd
Key : 66 Value : weq
Key : 7 Value : gdf
Key : 93 Value : nsa
Key : 8 Value : yes
Key : 43 Value : fsa
Key : 12 Value : mds

Elements of the HashMap after Sorting
**************************************
Key : 5 Value : asd
Key : 1 Value : cfd
Key : 43 Value : fsa
Key : 7 Value : gdf
Key : 12 Value : mds
Key : 93 Value : nsa
Key : 55 Value : qwe
Key : 50 Value : tes
Key : 66 Value : weq
Key : 3 Value : wer
Key : 8 Value : yes

How to Sort HashMap having Object Values ?

We have learnt how to sort Wrapper Objects, but in the real world situations you will be in a situation to sort object based on the particular attribute lets now see how we can achieve this.

Lets take a class Car which has two attributes color and wheels, we implement sorting of Car object based on wheels attribute

Car.java

public class Car 
{
    private String color;
    private Integer wheels;
    
    public Car(String color, int wheels) {
        this.color = color;
        this.wheels = wheels;
    }
    
    public String getColor() {
        return color;
    }
    public Integer getWheels() {
        return wheels;
    }
    @Override
    public String toString()
    {
        return ""+color+""+wheels;
    }
}

SortObjectValueHashMapExample.java

package com.javainterviewpoint.HashMap;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class SortObjectValueHashMapExample 
{
    public static void main(String args[])
    {
        final Map<String,Car> unsortedMap = new HashMap<String,Car>();
        
        Car c1 = new Car("Red",3);
        Car c2 = new Car("Blue",1);
        Car c3 = new Car("Green",4);
        Car c4 = new Car("Yellow",2);
        
        unsortedMap.put("Red Car",c1);
        unsortedMap.put("Blue Car",c2);
        unsortedMap.put("Green Car",c3);
        unsortedMap.put("Yellow Car",c4);
        
        //Print the Elements of the Map before Sorting
        System.out.println("Elements of the HashMap before Sorting");
        printMap(unsortedMap);
        
        Map<String,Car> sortedMap = new TreeMap<String,Car>(
                new Comparator()
                {
                    @Override
                    public int compare(String s1,String s2)
                    {
                        return unsortedMap.get(s1).getWheels().compareTo(unsortedMap.get(s2).getWheels());
                    }
                });
        sortedMap.putAll(unsortedMap);
        //Print the Elements of the Map after Sorting
        System.out.println("Elements of the HashMap after Sorting");
        printMap(sortedMap);
    }
    public static void printMap(Map<String,Car> map) {
        System.out.println("**************************************");
        for (Entry<String,Car> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() 
                                      + "  Value : " + entry.getValue());
        }
        System.out.println();
    }
}

Output :

Elements of the HashMap before Sorting
**************************************
Key : Green Car  Value : Green4
Key : Yellow Car  Value : Yellow2
Key : Red Car  Value : Red3
Key : Blue Car  Value : Blue1

Elements of the HashMap after Sorting
**************************************
Key : Blue Car  Value : Blue1
Key : Yellow Car  Value : Yellow2
Key : Red Car  Value : Red3
Key : Green Car  Value : Green4

Other interesting articles which you may like …

  • Java Collections – Deque Example in Java
  • How to use Java Collections Queue in Java
  • How to Reverse String in Java using String Tokenizer
  • How to remove an element from collection using Iterator Example
  • How to create read only List, Set, Map in Java?
  • How to Convert Array to ArrayList in Java?
  • Java ArrayList contains() Method Example
  • How to swap elements in an ArrayList
  • How to join two ArrayLists in java
  • Override toString() method of ArrayList in Java
  • Find Common Elements between two ArrayList in Java
  • Java ArrayList indexOf(Object o) Method Example
  • Java TreeMap values() Method Example
  • Java TreeMap floorKey() Method Example
  • Java HashMap putAll() Example
  • Java HashMap entrySet() Example
  • Java HashMap containsValue(Object value) Example
  • Java TreeSet descendingSet() Method Example
  • Java Vector toString() Example
  • Java Vector size() Example
  • Java LinkedHashSet add(E e) Method Example
  • Java LinkedList add(E e) Method Example

Filed Under: Core Java, HashMap, Java Tagged With: comparator(), hashmap, Java, Sort, Sort HashMap, TreeMap, values()

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·