We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › hashmap - how to get items sorted out of it
Page Index Toggle Pages: 1
hashmap - how to get items sorted out of it? (Read 1832 times)
hashmap - how to get items sorted out of it?
May 11th, 2008, 6:46pm
 
hello all,

does somebody know how to get items out of a hashmap in a sorted way? i found the hashmap example below in the hacks category (btw. very good) but unfortunately i was not able to "sort" the items by their wordcount ...

http://processing.org/hacks/doku.php?id=hacks:hashmap

thanks
benedikt

Code:

/*
hashmap taken from http://processinghacks.com/hacks:hashmap
@author Rick Companje
*/

Map words = new HashMap();

void setup() {
addWord("rick");
addWord("rick");
addWord("hi");
addWord("hi");
addWord("hi");
addWord("hi");
addWord("test");
printWords();
}

void addWord(String value) {
Integer n = (Integer)words.get(value);
int count = (n!=null ? n.intValue()+1 : 1);
words.put(value,new Integer(count));
}

void printWords() {
Set keys=words.keySet();
Iterator iter = keys.iterator();
while(iter.hasNext()){
String name = iter.next().toString();
println(name + " " + words.get(name));
}
}

void printWordsCountSorted() {
/*
????
the output should be:
hi 3 times
rick 2 times
test 1 time
*/
}
Re: hashmap - how to get items sorted out of it?
Reply #1 - May 11th, 2008, 7:46pm
 
HashMaps are unsorted by design unfortunately, to get it sorted you'd have to get the data out and into a custom class which implements Comparable, stick that in an array, and then use Arrays.sort() on it.
Re: hashmap - how to get items sorted out of it?
Reply #2 - May 12th, 2008, 12:05pm
 
thanks JohnG ... i found this example (sorting 2D array):

http://forum.java.sun.com/thread.jspa?threadID=683805&messageID=3982739

Code:


String[][] names = new String[3][2];
names[0][0] = "ann";
names[0][1] = "10";

names[1][0] = "barry";
names[1][1] = "5";

names[2][0] = "mark";
names[2][1] = "8";
for(int i = 0; i < names.length; i++) {
println(names[i][0] + ", " + names[i][1]);
}

java.util.Arrays.sort(names, new java.util.Comparator<String[]>() {
public int compare(String[] o1, String[] o2) {
if(Integer.parseInt(o1[1]) > Integer.parseInt(o2[1])) {
return 1;
}
else if(Integer.parseInt(o1[1]) < Integer.parseInt(o2[1])) {
return -1;
}
else {
return 0;
}
}

}
);
for(int i = 0; i < names.length; i++) {
println(names[i][0] + ", " + names[i][1]);
}




i think this is exactly what i need, but still i was not able to port it to processing. i always get a failure messages which i don't really understand (i'm new to java). especially the line
Code:

java.util.Arrays.sort(names, new java.util.Comparator<String[]>() {

brings always "an unexpected token: <" failure ... so any more hints would be welcome.

thanks
Re: hashmap - how to get items sorted out of it?
Reply #3 - May 13th, 2008, 11:49am
 
This is because this doesn't work on java 4 (the "<...>"), you can try to remove the "<String[]>" part, maybe it will work, not sure though ... also, what are the keys of your map? if they are "simple objects" (like and Integer or String) you don't need a comparator and you can call sort with only the array ...

... also you can try to use TreeMap (http://java.sun.com/j2se/1.4.2/docs/api/java/util/TreeMap.html) instead of HashMap, functionality is the same but implementation differs and it will return the values in ascending order (based on they key, not the value)

good luck
Re: hashmap - how to get items sorted out of it?
Reply #4 - May 15th, 2008, 8:50am
 
solved thanks to stefan. check code

Code:

import java.util.*;
import java.util.List;

Map words;

void setup() {
words = new TreeMap();

addWord("rick");
addWord("rick");
addWord("hi");
addWord("hi");
addWord("hi");
addWord("hi");
addWord("haus");
addWord("hi");
addWord("test");
addWord("hi");
addWord("hi");
addWord("stefan");

println("--unsorted:");
print(words);

println("\n--sorted by value:");
print(createMapSortedByValue());
}

void addWord(String value) {
Integer n = (Integer) words.get(value);
int count = (n != null ? n.intValue() + 1 : 1);
words.put(value, new Integer(count));
}

Map createMapSortedByValue() {
//create a Comparator for words
SortByValueComparator byValueComp = new SortByValueComparator(words);
//create a sorted treemap, sorted with byValueComp
SortedMap sortedWords = new TreeMap(byValueComp);
//add all elements from words
sortedWords.putAll(words);
//println(sortedWords.size());
//println(sortedWords.get("auto"));
return sortedWords;
}

void print(Map map) {
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
String name = (String) iter.next();
System.out.println(name + " " + map.get(name));
}
}

/**
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
* http://www.manticmoo.com/articles/jeff/programming/java/sorting-maps-by-value.php
*/
class SortByValueComparator implements Comparator {
Map words;

SortByValueComparator(Map words) {
this.words = words;
}

int compare(Object arg0, Object arg1) {
int val0 = ((Integer) (words.get(arg0))).intValue();
int val1 = ((Integer) (words.get(arg1))).intValue();

if (val0 < val1) {
return 1;
}
else if (val0 == val1) {
// same counts so compare names
return ((String) arg0).compareTo((String) arg1);
}
else {
return -1;
}
}
}

Page Index Toggle Pages: 1