[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 7067
  • Last Modified:

How to sort a set

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();
all.addAll(m.keySet());
all.addAll(m1.keySet());

Thanks
0
SuAeE
Asked:
SuAeE
1 Solution
 
objectsCommented:
Use a TreeSet

Set all = new TreeSet();
0
 
marklorenzCommented:
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));

Read more here:

Ordered Collections
http://mindprod.com/jgloss/sort.html#ORDERED
0
 
mbvvsatishCommented:
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
CEHJCommented:
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
 
CEHJCommented:
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
 
CEHJCommented:
Yet another error:

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

should be

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

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now