How to sort the elements in HashMap
Answers were Sorted based on User's Feedback
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 |
Answer / srinivasa
By implementing comparable interface we can sort the
HashMap
| Is This Answer Correct ? | 11 Yes | 2 No |
Answer / srinivasa
we can use to Collections.syncroniseMap() to synchronize
the HashMap
| Is This Answer Correct ? | 7 Yes | 12 No |
Can we add two byte variables and assign the result to a byte variable ? b=b1+b2 where b,b1,b2 are byte types
What is a functional interface?
Will the jvm load the package twice at runtime?
What does int [] mean in java?
What is the static keyword?
What is the difference between abstract class and interface1? What is an interface?
Can a singleton class be inherited?
what is mutability?which one is mutable String or StringBuffer?and why?give examples of each which shows the mutability of each String or StringBuffer
What is the advantage of preparedstatement over statement?
What are thread groups?
Differentiate between run time error and syntax error.
What is string data type?