Sort HashMap By Value Java

Sort HashMap By Value Java

This question is asked in many interview to check candidate ability to write logic quickly. Most of the time candidate fails:

package coding.test;

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 HashMapValueSorting {

	public static void main(String[] args) {
		
		Map<String, Person> map = new HashMap<>();
		
		Person person = new Person();
		person.setFirstName("C");
		map.put("person1", person);

		person = new Person();
		person.setFirstName("B");
		map.put("person2", person);
		
		person = new Person();
		person.setFirstName("A");
		map.put("person3", person);
		
		Set<Entry<String, Person>> set = map.entrySet();
		
		List<Entry<String, Person>> list = new ArrayList<Map.Entry<String,Person>>(set);
		
		Collections.sort(list, new Comparator<Entry<String, Person>>() {

			@Override
			public int compare(Entry<String, Person> o1, Entry<String, Person> o2) {
				
				return (o1.getValue().getFirstName().compareTo(o2.getValue().getFirstName()));
			}
		});
		
		for (Entry<String, Person> entry : list) {
			System.out.println("Key-->"+entry.getKey()+"  Value-->"+entry.getValue().getFirstName());
		}

	}

}
  • Output sort in natural order:

  • Now if you want to sort above HashMap in reverse order then just putt “-” or negative sign in-front of your return:

return (-o1.getValue().getFirstName().compareTo(o2.getValue().getFirstName()));

  • Complete program:
package coding.test;

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 HashMapValueSorting {

	public static void main(String[] args) {
		
		Map<String, Person> map = new HashMap<>();
		
		Person person = new Person();
		person.setFirstName("C");
		map.put("person1", person);

		person = new Person();
		person.setFirstName("B");
		map.put("person2", person);
		
		person = new Person();
		person.setFirstName("A");
		map.put("person3", person);
		
		Set<Entry<String, Person>> set = map.entrySet();
		
		List<Entry<String, Person>> list = new ArrayList<Map.Entry<String,Person>>(set);
		
		Collections.sort(list, new Comparator<Entry<String, Person>>() {

			@Override
			public int compare(Entry<String, Person> o1, Entry<String, Person> o2) {
				
				return (-o1.getValue().getFirstName().compareTo(o2.getValue().getFirstName()));
			}
		});
		
		for (Entry<String, Person> entry : list) {
			System.out.println("Key-->"+entry.getKey()+"  Value-->"+entry.getValue().getFirstName());
		}

	}

}

Leave a Reply

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