How to sort the elements in HashMap

Answers were Sorted based on User's Feedback



How to sort the elements in HashMap ..

Answer / 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

How to sort the elements in HashMap ..

Answer / srinivasa

By implementing comparable interface we can sort the
HashMap

Is This Answer Correct ?    11 Yes 2 No

How to sort the elements in HashMap ..

Answer / srinivasa

we can use to Collections.syncroniseMap() to synchronize
the HashMap

Is This Answer Correct ?    7 Yes 12 No

Post New Answer

More Core Java Interview Questions

What is native method in java?

0 Answers  


how to open and edit XML file in Weblogic???

0 Answers   Symphony,


What are the approaches that you will follow for making a program very efficient?

0 Answers  


How do you sort arraylist in descending order?

0 Answers  


What is interface and its use?

8 Answers   HCL,






Differece between class and generic class?

0 Answers   Tech Mahindra,


What does system.gc() and runtime.gc() methods do?

0 Answers  


Can vector have duplicates in java?

0 Answers  


What is deadlock and how to avoid this?

2 Answers  


they asked class A{} class B{} class c{} all the three class saved as a single file,there is no main method in the file and anothe class M.java class m { psvm(String args[]) { // here the parent class can access } }

2 Answers   DNS, IPSR Solutions,


What is arraylist e in java?

0 Answers  


I have a Person object with 5 variables and I want to store them in a file called Person.txt. What should I do?

3 Answers   KPIT,


Categories