How to sort the elements in HashMap

Answer Posted / jyoti

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

public class format {
public static void main(String args[]) {
Map<String, Person> people = new
HashMap<String, Person>();
Person jim = new Person("Jim", 25);
Person scott = new Person("Scott", 28);
Person anna = new Person("Anna", 23);
people.put(jim.getName(), jim);
people.put(scott.getName(), scott);
people.put(anna.getName(), anna);
// not yet sorted
ArrayList<Person> peopleByAge = new
ArrayList<Person>(people.values());
Collections.sort(peopleByAge, new
Comparator<Person>()
{
public int compare(Person o1,
Person o2)
{
return o1.getAge() -
o2.getAge();
}
});
for (Person p : peopleByAge) {
System.out.println(p.getName()
+ "\t" + p.getAge());
}
}
}
class Person
{
String name = null;
int age;
Person()
{

}
Person(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
}

Is This Answer Correct ?    16 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Why parsing is done?

736


What is the purpose of interface?

786


How do I stop concurrentmodificationexception?

735


Is nan false?

725


What is difference between module and function?

770


What are facelets templates?

790


What is bubble sort in java?

847


What are the legal parameters?

705


What is an anonymous class in java?

777


How are multiple inheritances done in Java?

850


Which list does not allow duplicates in java?

717


Is string is a keyword in java?

741


Tell me the Importent classes in net package?

1763


Why lambda expression is used in java?

769


What is string [] args?

786