Solved

# How to sort a set

Posted on 2007-08-01
7,053 Views
How can I sort the following set in ascending order by the keys in the hashmaps m and m1 ?
bth the keys in the hashmaps are date strings.

Set all = new HashSet();

Thanks
0
Question by:SuAeE

LVL 92

Accepted Solution

Use a TreeSet

Set all = new TreeSet();
0

LVL 12

Expert Comment

The Set contract is to not sort the elements.
If you want to maintain a set use a TreeSet:

Set myOldSet ......
new TreeSet(myOldSet);

Or if you just want a quick sort without bothering with Set restrictions,
do:

Collections.sort(new ArrayList(myOldSet));

Ordered Collections
http://mindprod.com/jgloss/sort.html#ORDERED
0

LVL 10

Expert Comment

0

LVL 86

Expert Comment

List dates = new ArrayList(all.entrySet());
Collections.sort(dates, new Comparator() {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); // (or whatever the format is)
public int compare(Object o1, Object o2) {
int result = 0;
try {
result = df.parse(o1.toString()).compareTo(o2.toString());
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
});
// Entry List ´dates´ now sorted
0

LVL 86

Expert Comment

Sorry, that should have been

List dates = new ArrayList(all.entrySet());
Collections.sort(dates, new Comparator() {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); // (or whatever the format is)
public int compare(Object o1, Object o2) {
int result = 0;
try {
String d1 = ((Map.Entry)o1).getKey().toString()
String d2 = ((Map.Entry)o2).getKey().toString()
result = df.parse(d1).compareTo(d2);
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
});
// Entry List ´dates´ now sorted
0

LVL 86

Expert Comment

Yet another error:

>>result = df.parse(d1).compareTo(d2);

should be

result = df.parse(d1).compareTo(df.parse(d2));
0

## Featured Post

### Suggested Solutions

If you have upgraded to Java2 update 10 on a Microsoft Windows client, you may have discovered that your Java application does not work as it did before.  For example, the colors of your Java2D graphic may be all wrong for no apparent reason. Aft…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input: