• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

sort HashMap by Key object's value

 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,

I have HashMap which contains key as Employee object and value as ArrayList.

Employee object contains employeeName, age, sex etc..

I want to sort HashMap based on the employee name ..


Please provide me the solution for this situation....


Thanks in advance
 
Marshal
Posts: 70334
283
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try an implementation of the SortedMap interface instead.
 
Kathiresan Chinnasamy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you Campbell Ritchie for your reply....

this solution might not work some times. Suppose i want to sort by age..

is this work fine ?
 
Sheriff
Posts: 22002
107
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can still use TreeMap - just provide a Comparator<Employee> in the constructor. You just have to make sure that the Comparator never returns 0 when comparing two objects, or these objects will be regarded as equal and only one of them will be stored. So if you want to sort on age only, you still have to use the other fields after that:
 
Kathiresan Chinnasamy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Rob Prime ..


Could you explain little bit more ?

I tried it but i couldn't find out the solution

please get me example if you have it
 
Rob Spoor
Sheriff
Posts: 22002
107
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out the API for java.util.TreeSet and java.util.Comparator.

As to the separate field comparisons:
- use String's compareTo or compareToIgnoreCase method for Strings
- use the compareTo method for any other comparable
- use val1 - val2 for char, short and byte
- use Float.compare(val1, val2) and Double.compare(val1, val2) for floats / doubles
- use (val1 < val2 ? -1 : (val1 > val2 ? 1 : 0)) for int and long; simple subtraction may lead to overflows. For instance, Integer.MIN_VALUE - 1 is quite positive
 
Kathiresan Chinnasamy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,

If i use TreeMap , i got class cast exception

for Example

please see this code

import java.util.ArrayList;
import java.util.TreeMap;



public class TestDao {

public static void main(String[] args) throws Exception{

treemapEx();
}

static void treemapEx() {

TreeMap treeMap = new TreeMap() ;


for(int i=5 ; i>0 ;i-- ) {

Prodatto1Test prodotto = new Prodatto1Test() ;

prodotto.setA(i) ;
prodotto.setB(i) ;
prodotto.setAb("SSSS") ;

ArrayList list = new ArrayList() ;

list.add(prodotto) ;

treeMap.put(prodotto, list) ;

System.out.println("List Addeded");
}

for(int i=0 ; i<5 ;i++ ) {
System.out.println("TreeMap Value" + treeMap.get("one"+i));
}

}

}

OutPut is :

List Addeded
Exception in thread "main" java.lang.ClassCastException: it.sella.Prodatto1Test
at java.util.TreeMap.compare(TreeMap.java:1093)
at java.util.TreeMap.put(TreeMap.java:465)
at TestDao.treemapEx(TestDao.java:39)
at TestDao.main(TestDao.java:21)



The very first time Obj is added into the TreeMap where as next time i got this exception



This bean class:

2.

package it.sella.entity;

public class Prodatto1Test {

private int a ;
private int b ;
private String ab ;

public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public String getAb() {
return ab;
}
public void setAb(String ab) {
this.ab = ab;
}

}

 
Rob Spoor
Sheriff
Posts: 22002
107
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the TreeMap API clearly specifies that either the elements must implement Comparable (and be Comparable to each other; String and Integer don't mix well), or you must provide a Comparator to the TreeMap constructor.

Also note that mutable objects are a bad choice for keys for nearly all Map implementations. If the hash code changes with (Linked)HashMap, and the comparison changes with TreeMap, then you can never find the entry again using the get or put methods. This is caused by the way entries are stored and retrieved.

(Linked)HashMap uses hashCode first to limit the number of elements to check (see hash table), then uses equals to check all elements with the same hash code. If the hash code changes, the (Linked)HashMap will check a different bucket and therefore never find the key.

TreeMap works similarly, but uses compareTo / compare. It checks the root of the binary tree, and decides to go left or right, depending on the return value. If that value switches, you will check the wrong side and will never find the object again.


So I stress again: if you use an object in a map, make sure that the fields used in hashCode / compareTo / compare will never change while the object is used as a key. Java Beans especially make very bad keys since all fields can change. You can still use a Java Bean or other mutable objects as key, just ensure that it does not change while it is a key.
 
Kathiresan Chinnasamy
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rob Prime,

I got the solution by implements Comparable interface...


Thank you everyone to help me out for this solution
 
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
k
 
reply
    Bookmark Topic Watch Topic
  • New Topic