Skip to content

  • Home
  • Core Java
    • Write Your Own Immutable Class In Java
    • Write Your Own Singleton Class In java
    • Java Concurrent Package
    • Java Stream Revisited
    • Print odd and even numbers using thread
    • SOLID principles
    • Comparable Vs Comparator
    • Sort HashMap/TreeMap based on value
    • Deep and Shallow Copy in Java with examples
    • Find the frequency of each character in a String
    • How to avoid duplicate Employee objects in HashSet ?
  • Spring
    • Loose Coupling & Dependency Injection
    • Bean Scope
    • Spring Bean Lifecycle
    • IoC Container Vs Application Context Vs Bean Factory
    • @Component Vs @Service @Repository Vs @Controller
    • How to read properties file in Spring
    • Spring AOP (Aspect Oriented Programming)
    • @Component Vs @Bean in Spring
    • Exception Handling in SpringBoot
    • XML configuration Vs Annotations configuration in Spring
    • Spring Data JPA
    • Spring Data REST
  • Spring Security
    • Spring Security with Form, Basic and JWT
    • Security Configuration in Spring Boot Apps
    • Security Protocols & Frameworks
    • Okta OAuth 2.0 SSO with Springboot
    • Spring Boot 2.x Security using Username Password
    • Spring Boot 2.x Security using JWT
    • Spring Boot 3.x Security using Username Password
    • Spring Boot 3.x Security using JWT
  • Microservices
    • Spring Cloud Config (Server & Client)
    • Spring Boot Microservices Tutorial (Part 1 of 2)
    • Spring Boot Microservices Tutorial (Part 2 of 2)
    • Circuit Breaker – Resilience4j
    • The Twelve-Factor App Principles
  • Event Driven Microservices
    • What is Event Driven Microservice ?
    • What is Saga Design Pattern ?
    • What is CQRS Design Pattern ?
  • Spring AI
    • ChatGPT API + SpringBoot Integration
  • Hibernate & JPA
    • JPA vs JDBC
    • CRUD Example Using Spring Boot JPA + H2 + Gradle
    • MongoDB Atlas With Spring Boot Example
    • Transaction Management
    • Relationships in JPA & Hibernate
    • Hibernate First & Second Level Cache
    • Spring Boot Flyway Postgres
  • DevOps
    • What is Devops ?
    • Docker
    • Kubernetes (K8S)
    • Jenkins
    • Infrastructure As Code
  • Functional Programming
    • Functional Programming Vs Structured Programming
    • Java 8 Programs For Interview
    • Predicate, Function, Consumer and Supplier in Java 8
    • Sort a List having Employee objects using Java 8
    • Find Employee from List using Java 8
  • AWS
    • AWS S3
    • AWS EC2
    • EC2 Solutions Architecting
    • How to create an EC2 instance ?
    • How to connect to AWS EC2 instance ?
    • Deploy application to AWS
    • AWS Lambda Java Tutorial
    • Spring Cloud Functions
    • How to Start/Stop AWS ECS automatically using Java Spring?
    • Container Solution in AWS
    • AWS SQS, SNS, MQ and Kinesis
    • Databases in AWS
    • AWS VPC: Peering, Endpoint, VPN, Gateways- Internet, NAT, DX
    • Machine Learning in AWS
    • Storage Solutions in AWS
    • AWS ASG (Auto Scaling Group)
  • AWS Certifications
    • SAA-C03
      • Design Cost-Optimized Architectures
    • AWS Certified Solution Architect-Associate
      • Question 1
  • Kafka
    • Apache Kafka
    • Kafka Producer & Consumer Example Using Spring boot & Conduktor
  • Angular
    • Angular Tutorial – Part 1
    • Angular Tutorial – Part 2
  • Miscellaneous
    • How to add a project to Git/GitHub/GitLab
    • How to Clone a project from Git/GitLab using Git Bash
    • How to query Oracle tables based on some date ?
    • How to highlight text in WordPress ?
    • How to add Page Jumps in WordPress page ?
  • Interview Preparation
    • Core java interview questions
    • Java Threads Interview Questions
  • Contact Me
  • Toggle search form

Sort HashMap/TreeMap based on value

How to sort HashMap/TreeMap based on value ?

Solution Logic: First we will have a normal HashMap/Treemap object and put some objects to it. Then we will put the same object to another TreeMap object.

class ValueComparator implements Comparator{
    Map map;
    public ValueComparator(Map map) {
        this.map=map;
    }    
    public int compare(Object o1, Object o2) {
		int i1=(Integer)map.get(o1); 
		int i2=(Integer)map.get(o2); 		
		return i1-i2;
        //return i1.compareTo(i2);//If i1 and i2 were of Class type instead of primitives
    }    
}

public class Manager {
	public static void main(String[] args){
		
        Map map=new HashMap();
        map.put("B", 5);
        map.put("A", 4);
        map.put("C", 2);
        map.put("E", 3);
        map.put("D", 1);
        map.put("G", 7);
        map.put("F", 6);        
        
        System.out.println("Before sorting:"+map);        
        Map map2=new TreeMap(new ValueComparator(map));
        map2.putAll(map);//only when you start putting the objects again, it will start re-arranging
        System.out.println("After sorting:"+map2);       	
	}
}

Below is another example using an class type (Employee object):

class Employee implements Comparator{
	int age;
	Map map;
	public Employee(int age) {
		this.age=age;
	}
	public int compare(Object o1, Object o2) {
		
		Employee e1=(Employee)o1;
		Employee e2=(Employee)o2;
		return e1.age - e2.age;		
	}	
	public String toString() {
		return String.valueOf(age);
	}
}

class ValueComparator implements Comparator{
	Map map;
	public ValueComparator(Map map) {
		this.map=map;
	}	
	public int compare(Object o1, Object o2) {		
		Employee e1 = (Employee) map.get(o1);
		Employee e2 = (Employee) map.get(o2);
		return e1.age - e2.age;
	}	
}

public class Manager{
	public static void main(String[] args) {
		Employee e1=new Employee(41);
		Employee e2=new Employee(35);
		Employee e3=new Employee(10);
		
		Map map=new TreeMap(new Employee(5));//
		
		map.put(e1, e2);
		map.put(e3, e3);
		map.put(e2, e1);		
		
		System.out.println(map);
		Map map2=new TreeMap(new ValueComparator(map));
		map2.putAll(map); //only when you start putting the objects again, it will start re-arranging
		System.out.println(map2);		
	}		
}

Copyright © 2025 .

Powered by PressBook Blog WordPress theme