In this example I am going to show you an example on using Comparator in HashMap will show you how to use Comparator
to sort values in HashMap
. I will use custom object as a key in the HashMap. The object which is used as an object as a key in HashMap must override hashCode()
and equals()
methods.
Prerequisites
Knowledge of Java
Related Posts:
Creating POJO Class
I will create a simple POJO class Book that will act as a key in HashMap. As the instance of this class is used as a key, so I am overriding hashCode()
and equals()
method in the Book class.
I will check both title
and author
attributes for the equality check for the two Book
objects.
If you are using Eclipse then you can generate these two methods – hashCode()
and equals()
– from the option.
Shortcut keys in Windows system in Eclipse are Alt + Shift + S. On popup window click on Generate hashCode() and equals().
package com.roytuts.java.comparartor.in.hashmap;
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
@Override
public String toString() {
return "Book [title=" + title + ", author=" + author + "]";
}
}
Main Class
Create below main class which will test the user defined objects as keys in HashMap.
I will also use Comparator
to sort the elements in HashMap
. I will use comparator()
method of Comparator
interface in pre-Java 8 style and lambda expression.
I am using here Collections.sort()
method to sort our list of Book
objects.
package com.roytuts.java.comparartor.in.hashmap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HashMapComparator {
public static void main(String[] args) {
Map<Book, String> bookMap = new HashMap<>();
bookMap.put(new Book("Java", "James Gosling"), "Java");
bookMap.put(new Book("C++", "Bjourn Stroustup"), "C++");
bookMap.put(new Book("C", "Denish Ritche"), "C");
bookMap.put(new Book("Databse", "C J Date"), "Database");
System.out.println("Unsorted HashMap Values");
System.out.println("-----------------------");
bookMap.forEach((k, v) -> System.out.println(k + " => " + v));
System.out.println();
Set<Entry<Book, String>> set = bookMap.entrySet();
List<Entry<Book, String>> list = new ArrayList<Entry<Book, String>>(set);
Collections.sort(list, new Comparator<Map.Entry<Book, String>>() {
@Override
public int compare(Entry<Book, String> b1, Entry<Book, String> b2) {
return (b1.getValue()).compareTo(b2.getValue());
}
});
System.out.println("Sorted HashMap Values");
System.out.println("---------------------");
list.forEach(item -> System.out.println(item.getKey() + " => " + item.getValue()));
Collections.sort(list, (b1, b2) -> b1.getValue().compareTo(b2.getValue()));
System.out.println();
System.out.println("Sorted HashMap Values (Lambda Expression)");
System.out.println("-----------------------------------------");
list.forEach(item -> System.out.println(item.getKey() + " => " + item.getValue()));
}
}
Using the lambda expression you can replace the below code snippets in the above class.
The Comparator
interface is a functional interface and it has only one method and annotated with @FunctionalInterface
so that no further new method can be added and lambda expression can be used easily.
Collections.sort(list, new Comparator<Map.Entry<Book, String>>() {
@Override
public int compare(Entry<Book, String> b1, Entry<Book, String> b2) {
return (b1.getValue()).compareTo(b2.getValue());
}
});
by
Collections.sort(list, (b1, b2) -> b1.getValue()).compareTo(b2.getValue());
Testing the Program
Run the above main class and you will get the below output:
Unsorted HashMap Values
-----------------------
Book [title=C++, author=Bjourn Stroustup] => C++
Book [title=Java, author=James Gosling] => Java
Book [title=C, author=Denish Ritche] => C
Book [title=Databse, author=C J Date] => Database
Sorted HashMap Values
---------------------
Book [title=C, author=Denish Ritche] => C
Book [title=C++, author=Bjourn Stroustup] => C++
Book [title=Databse, author=C J Date] => Database
Book [title=Java, author=James Gosling] => Java
Sorted HashMap Values (Lambda Expression)
-----------------------------------------
Book [title=C, author=Denish Ritche] => C
Book [title=C++, author=Bjourn Stroustup] => C++
Book [title=Databse, author=C J Date] => Database
Book [title=Java, author=James Gosling] => Java
Hope you got an idea how to use Comparator
in HashMap
to sort the objects.