• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorting in TreeMap  RSS feed

 
samir ware
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Ranchers
I am using TreeMap so that all my data will be sorted on the basis of keys. It work fine for me except that it sorts all the data based on the upper case and lower case . For e.g. If my keys are A,c,E,D,b the sorted output will be A,D,E,b,c . However I dont want to sort the data based on the case sensitivity. The desire output for me is A,b,c,D,E . Is there any collection which can gimme this kinda sorting. Using comparator is one of the option . But I am just trying to explore something apart from comparator.
Thanks
Samir
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to use TreeMap and customize the order, then you have two options:

  • Write your own Comparator and pass it to the constructor of TreeMap.
  • Make the class that you use for the keys implement interface Comparable, and add the appropriate compareTo() method to your key class.


  • If you are using normal Strings as the keys, then the second isn't going to work, because you can't change the implementation of class String.
     
    Rob Spoor
    Sheriff
    Posts: 21133
    87
    Chrome Eclipse IDE Java Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Try using String.CASE_INSENSITIVE_ORDER as the Comparator.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!