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
Explain importance of inheritance in java?
Can we call the constructor of a class more than once for an object?
Explain about procedural programming language or structured programming language and its features?
What are packages in java?
Is logger a singleton?
What are the main features of java?
Can subclass overriding method declare an exception if parent class method doesn't throw an exception?
What is a condition in programming?
os is developed in c no java is more secured then c na why dont the os developed is developed using java
what is meant by Garbage collection?
What is array list in java?
What restrictions are placed on method overriding?
what is ststic with example
How does java pattern compile work?
Why to use nested classes in java? (Or) what is the purpose of nested class in java?