aspose file tools*
The moose likes Beginning Java and the fly likes Display the sortedMap/TreeMap in descending order: Alternative? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Display the sortedMap/TreeMap in descending order: Alternative?" Watch "Display the sortedMap/TreeMap in descending order: Alternative?" New topic
Author

Display the sortedMap/TreeMap in descending order: Alternative?

H Paul
Ranch Hand

Joined: Jul 26, 2011
Posts: 471
    
    4
Given:

Map<String, String> sortedMap = new TreeMap<String, String>();

sortedMap =

A, A.JPEG
B, B.JPEG
C, C.JPEG
D, D.JPEG

To display the sortedMap in descending order, I did:



What are the alternative to achieve the same thing instead of using loop DESCENDINGLY as I did?
1M Thanks.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4422
    
    8

Have a look at the methods TreeMap.descendingMap() and TreeMap.descendingKeySet() - I think you might find one of those useful.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
There is a method which returns a set of keys in reverse order.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  17

[edit] Nevermind :P [/edit]
H Paul
Ranch Hand

Joined: Jul 26, 2011
Posts: 471
    
    4
(Is there any thing that travel faster the speed of light? Yes. All of YOU)

1. TreeMap has mentioned methods since JDK1.6


2. What if one does not use JDK1.6 still for some reason?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4422
    
    8

In that case, how about using Collections.reverseOrder()? That will give you a Comparator that sorts in reverse (natural) order. So once you've put them in an array or List, sort it with that then iterate as usual.

Whether that's simpler than what you're doing now is up to you!
H Paul
Ranch Hand

Joined: Jul 26, 2011
Posts: 471
    
    4


Arrays.sort(keys, Collections.reverseOrder());

If this is what you mean.

then I prefer it than the for (int i=keys.length-1;i>-1;i--)
because I don't have to be remember/careful about the numeric index boundary - ArrayIndexOutOfBoundsException.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4422
    
    8

Yes, that's what I was thinking of.

(Assuming it works. If it didn't, then no, I meant something completely different )
H Paul
Ranch Hand

Joined: Jul 26, 2011
Posts: 471
    
    4
(Assuming it works. If it didn't, then no, I meant something completely different )


To err is human. To forgive is divine.

(It works!)

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
Well done
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Display the sortedMap/TreeMap in descending order: Alternative?