• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Display the sortedMap/TreeMap in descending order: Alternative?

 
H Paul
Ranch Hand
Posts: 471
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have a look at the methods TreeMap.descendingMap() and TreeMap.descendingKeySet() - I think you might find one of those useful.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50168
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a method which returns a set of keys in reverse order.
 
Stephan van Hulst
Bartender
Posts: 6311
77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[edit] Nevermind :P [/edit]
 
H Paul
Ranch Hand
Posts: 471
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(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
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 471
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 471
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(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
Pie
Posts: 50168
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic