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
What are the 6 boolean operators?
Why wait and notify methods are declared in object class?
What methods are used to get and set the text label displayed by a button object?
Why do we need singleton?
What is ascii code?
What is the difference between actual and formal parameters?
What is parsing a sentence?
What are the approaches that you will follow for making a program very efficient?
What does the string method compareto () do?
What are the access modifiers available in java?
What is java reflection?
How do you generate random numbers in java?
In a program, initializing an array of 100 KB is throwing an out of memory exception while there is 100 MB of memory available. Why?
Is there any difference between synchronized methods and synchronized statements?
How do you bind variables?