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

What is a byte array?

859


design an lru cache in java?

764


What is immutable state?

751


What do you mean by a JVM?

840


Explain an algorithm to find depth of a binary tree.

808


What is equals method in java?

760


What happens when you add a double value to a string?

777


What about main thread in java?

882


What is the replace tool?

780


How you can force the garbage collection?

762


What interface is extended by awt event listeners?

831


What is string substring?

821


What is navigable map in java?

757


Is it possible for a yielded thread to get chance for its execution again?

740


What is a lock or purpose of locks in java?

805