Sorting a HashMap

I've a hashmap and i would like to sort it..

I've looked through the forum... but i still can't gather how i can go about solving it..

i changed my hashmap to treemap as i wanted to sort based on the key.

key is an integer value

and value of hashmap is a double.

please help/suggest..

[324 byte] By [gemithya] at [2007-10-2 13:01:04]
# 1

You can't sort a HashMap (or a Hash - anything) because the nature of the beast is that it's based on a "hashing algorithm" which means that a given set of keys will order themselves a certain way in a table of a give size, but that order is effectively random. The nature of the table fixes the order.

TreeMap will autmatically maintain your integers in order. If you want the "natural" order of integer keys then you don't need to supply a comparitor because Integer implements Comparable.

(You can't sort a TreeMap either, but you can controll the way a particular TreeMap orders it's entries).

malcolmmca at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 2

>>>TreeMap will autmatically maintain your integers in order.

if that's the case, do i simply do:

public void sorthashmap()

{

TreeMap myTreeMap;

myTreeMap = new TreeMap(hashMap);

}

would i need to return something? or convert it back to hashmap?

gemithya at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 3
*why* do you need to sort the HashMap? Are you wanting to retrieve its entries in order or something?
jagulara at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 4

yes.

im currently having the key values

e.g a string: 3:1.0 5:1.0 29:1.0 30:1.0 7:1.0

ignoring the ":", notice that my key is the left hand object of ":" and my value is the right hand object of ":"

however my hashmap cant order the keys regardless of the values... i wanted them in ascending order smalll to big

3:1.0 5:1.0 7:1.0 29:1.0 30:1.0

Please kindly help okie?

gemithya at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 5

I don't understand why...

I use:

TreeMap myTreeMap;

myTreeMap = new TreeMap(hashMap);

String result="";

Collection lines = myTreeMap.values();

Iterator i = lines.iterator();

Set words = myTreeMap.keySet();

for(Iterator it=words.iterator(); it.hasNext();)

{

result += (String)it.next() + " : " + (String)i.next() + " ";

}

System.out.println(result);

and nothing is displayed :(

gemithya at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 6

Map hashmap;

List l = new ArrayList(hashmap.keySet());

Collections.sort(l);

Object key, value;

for(Iterator ito = l.iterator(); ito.hasNext();){

key = ito.next();

value = hashmap.get(key);

}

da.futta at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 7

> >>>TreeMap will autmatically maintain your integers

> in order.

>

> if that's the case, do i simply do:

> > public void sorthashmap()

> {

>TreeMap myTreeMap;

>myTreeMap = new TreeMap(hashMap);

> }

>

> would i need to return something? or convert it back

> to hashmap?

No you can't sort a Map use the TreeMap instead of the HashMap and it will maintain the keys in their natural order. The above code would copy the entries from a HashMap into a TreeMap and you could then iterate over the TreeMap but really, why bother? Just us a TreeMap instead of a HashMap in the first place.

malcolmmca at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 8

Hi,

I tried to use yours also:

List l = new ArrayList(hashMap.keySet());

Collections.sort(l);

Object okey, ovalue;

for(Iterator ito = l.iterator(); ito.hasNext();){

okey = ito.next();

ovalue = hashMap.get(okey);

result += (String)okey + " : " + (String)ovalue + " ";

}

System.out.println(result);

but why is it that result is always null?

i don't get it... *in desperate help*

gemithya at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 9

Hi Malcolm.

TreeMap myTreeMap;

myTreeMap = new TreeMap(hashMap);

String result="";

Collection lines = myTreeMap.values();

Iterator i = lines.iterator();

Set words = myTreeMap.keySet();

for(Iterator it=words.iterator(); it.hasNext();)

{

result += (String)it.next() + " : " + (String)i.next() + " ";

}

System.out.println(result);

i have tried using a TreeMap...but i don't know why i cant print anything out...

i have to convert the hashmap to a treemap since it has been used in the first place by another person... and have developed from there...

please help. thanks!

gemithya at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 10
I tried to display the hashmap size as well..there are indeed variables inside.but i just cant display my result variable. :(
gemithya at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 11
> but why is it that result is always null?> > i don't get it... *in desperate help*If the result is null, it means your map is empty in the first place.
da.futta at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 12
I thought so too the reason why the string would return null butwhen i do:List l = new ArrayList(hashMap.keySet());System.out.println("here is the size"+hashMap.size());it do return me a size..
gemithya at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 13

> > but why is it that result is always null?

> >

> > i don't get it... *in desperate help*

>

> If the result is null, it means your map is empty in

> the first place.

Or maybe it is a custom Map implementation ? Maybe it's buggy and keySet() returns an empty Set ?

Have you had a result > 0 when you called hashmap.size() ? If yes, then try outputting hashmap.keySet().size().

da.futta at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 14

You could try checking myTreeMap.size()

Using two separated iterators may be a little iffy. Better something like:

Iterator it = myTreeMap.entrySet().iterator();

while(it.hasNext()) {

Map.Entry entry = (Map.Entry)it.next();

result += (String) entry.getKey() + ":" + (String)entry.getValue() + " ";

}

I confess, though, I can't see why your code isn't working.

malcolmmca at 2007-7-13 10:21:36 > top of Java-index,Java Essentials,Java Programming...
# 15

> Or maybe it is a custom Map implementation ? Maybe

> it's buggy and keySet() returns an empty Set ?

> Have you had a result > 0 when you called

> hashmap.size() ? If yes, then try outputting

> hashmap.keySet().size().

it's a custom map...

have tried to display keySet...the size is the same as hashmap size.

but strangely no result come out..

sigh... i think it's buggy. dont know why why why

gemithya at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 16

> > > but why is it that result is always null?

> > >

> > > i don't get it... *in desperate help*

> >

> > If the result is null, it means your map is empty

> in

> > the first place.

>

> Or maybe it is a custom Map implementation ? Maybe

> it's buggy and keySet() returns an empty Set ?

> Have you had a result > 0 when you called

> hashmap.size() ? If yes, then try outputting

> hashmap.keySet().size().

gemithya at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 17

> it's a custom map...

>

> have tried to display keySet...the size is the same

> as hashmap size.

>

> but strangely no result come out..

>

> sigh... i think it's buggy. dont know why why why

Hmm. Could you post the code of the keySet() method in that class ?

Also, you could try:

Map hashmap;

if( hashmap.keySet().size() > 0 ){

if( ! hashmap.keySet().iterator().hashNext() ){

System.err.println("The iterator is crap !");

}

else if( ! hashmap.containsKey(hashmap.keySet().iterator().next()) ){

System.err.println("The iterator is crap !");

}

}

da.futta at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 18
Not much point in looking at functions of the HashMap, it's the TreeMap that's giving the problem now.print the size() of the TreeMap, and try iterating over the entrySet().
malcolmmca at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 19

Hi mind if you all look at this for a while..

public String sortHashSet()

{

TreeMap myTreeMap;

myTreeMap = new TreeMap(hashMap);

String result="";

try{

List l = new ArrayList(hashMap.keySet());

Iterator it = myTreeMap.entrySet().iterator();

while(it.hasNext()) {

Map.Entry entry = (Map.Entry)it.next();

result += (String) entry.getKey() + ":" + (String)entry.getValue() + " ";

}

System.out.println("hello" + myTreeMap.size());

}

catch(Exception e)

{ System.out.println(e.getMessage()); }

return result;

}

this is my entire code that is giving me problem...

STRANGELY it dosnt even go to the hello statement? what's wrong?

gemithya at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 20

> Not much point in looking at functions of the

> HashMap, it's the TreeMap that's giving the problem

> now.

It's not a HashMap, the OP just said it was a custom Map implementation.

Are you sure the problem's with the TreeMap now ? I don't think so. OP, could you please clarify ?

da.futta at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 21
Maybe your'e getting an Exception with an empty message (this kind of catch clause is asking for trouble).At the least put e.printStackTrace(); in the catch block.Maybe sortHashSet isn't even being called.
malcolmmca at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 22
> STRANGELY it dosnt even go to the hello statement?> what's wrong?Either you haven't recompiled or there's an Exception thrown.
da.futta at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 23

> > Not much point in looking at functions of the

> > HashMap, it's the TreeMap that's giving the

> problem

> > now.

>

> It's not a HashMap, the OP just said it was a custom

> Map implementation.

> Are you sure the problem's with the TreeMap now ? I

> don't think so. OP, could you please clarify ?

sorry sorry it's my fault. the HashMap was not custom...

rather now im using a class that actually creates HashMap

and yup the string result always display null...cause of exceptions..

now i print stack trace...there's a whole lot of exceptions out...

sigh my programming isnt good.

please pardon me.

now i got to see what's the problem of the exceptions.

gemithya at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 24
> and yup the string result always display null...cause> of exceptions.. > > now i print stack trace...there's a whole lot of> exceptions out...Let me guess: ClassCastExceptions because the keys are not Comparable ?
da.futta at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 25

yes u are absolutely right!

now got some improvements!

manage to sort the keys BUT unfortunately it's accoding to alphabetical order:

14:2.0 24:1.0 29:1.0 3:1.0 30:1.0 35:3.0 4:4.0 5:1.0 7:1.0

note: keys are on the left of ":" and value on the right...

hmm...im using this now:

List l = new ArrayList(hashMap.keySet());

Collections.sort(l);

Object okey, ovalue;

for(Iterator ito = l.iterator(); ito.hasNext();){

okey = ito.next();

ovalue = hashMap.get(okey);

result += (String) okey + ":" + ((Weight)ovalue).getValue() + " ";

}

any suggestions?

gemithya at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 26

> manage to sort the keys BUT unfortunately it's

> accoding to alphabetical order:

>

> any suggestions?

Yes: make your map contains instances of java.lang.Integer as keys, not simply Strings consisting of digits.

Or use a custom comparator, like:

Comparator c = new Comparator(){

public int compare(Object o1, Object o2){

int i1 = Integer.parseInt(o1.toString()), i2 = Integer.parseInt(o2.toString());

return i1 - i2;

}

};

List l = new ArrayList(hashmap.keySet());

Collections.sort(l, c);

...

da.futta at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 27
great thanks for help Da Futt!!! :)and Malcolm as wellI think I can go and try out yours now..May both of you be blessed and many happy things come along your way! :)Cheers!!!!!THANK YOU SO MUCH!
gemithya at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 28
> great thanks for help Da Futt!!! :)You're welcome. How have you done it in the end ?
da.futta at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...
# 29
yes, thank you so much!! it's working perfectly now...Thank you very much!!!! Really appreciate it :)
gemithya at 2007-7-20 21:43:45 > top of Java-index,Java Essentials,Java Programming...