File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes sort HashMap by Key object's value Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "sort HashMap by Key object Watch "sort HashMap by Key object New topic
Author

sort HashMap by Key object's value

Kathiresan Chinnasamy
Ranch Hand

Joined: Jan 01, 2008
Posts: 65
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
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32644
    
    4
Try an implementation of the SortedMap interface instead.
Kathiresan Chinnasamy
Ranch Hand

Joined: Jan 01, 2008
Posts: 65
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 ?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19216

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:


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
Kathiresan Chinnasamy
Ranch Hand

Joined: Jan 01, 2008
Posts: 65
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

Joined: Oct 27, 2005
Posts: 19216

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

Joined: Jan 01, 2008
Posts: 65
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

Joined: Oct 27, 2005
Posts: 19216

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

Joined: Jan 01, 2008
Posts: 65
Hi Rob Prime,

I got the solution by implements Comparable interface...


Thank you everyone to help me out for this solution
Khaled Mahmoud
Ranch Hand

Joined: Jul 15, 2006
Posts: 360
k


SCJP, SCJD,SCWCD,SCDJWS,SCEA 5 MCP-C#, MCP-ASP.NET - http://www.khaledinho.com/
Life is the biggest school
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: sort HashMap by Key object's value
 
Similar Threads
sort a map or arraylist according to the value of the object inside
Help pls -Urgent(logic:iterate)
arrylist doubt
Problems w/ a HashMap
Sort and Print HashMap - Please Help