• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Can I sort String arrays?

 
Ranch Hand
Posts: 349
Hibernate Eclipse IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is there a way to sort a String array? I am using tree which gives a list of picked nodes through request ParameterValues. I am storing it to a String array. Can I sort these values?

Ananth Chellathurai
 
Marshal
Posts: 79475
379
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, it is easy since String implements the Comparable interface; you can use s1.compareTo(s2).
 
Ananth Chellathurai
Ranch Hand
Posts: 349
Hibernate Eclipse IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So what should I compare to? I just want my string array to be sorted alphabetically.

Ananth
 
Author
Posts: 3473
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



If you have special requirements


class test {

public static void main(String[] args) {
String words[] = { "Good", "Bad", "Ugly" };
Comparator<String> best = new Comparator<String>() {
public int compare(String s1, String s2) {
return s2.charAt(1) - s1.charAt(1}
};
Arrays.sort(words);
System.out.println(words[0]);
System.out.println(words[1]);
System.out.println(words[2]);
}
}


[ September 15, 2008: Message edited by: arulk pillai ]
 
Ananth Chellathurai
Ranch Hand
Posts: 349
Hibernate Eclipse IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot Arul. I will use this in my implementation.

Ananth Chellathurai
 
Sheriff
Posts: 22789
131
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You may want to use String.CASE_INSENSITIVE_ORDER if you want to sort it while ignoring the case.
 
reply
    Bookmark Topic Watch Topic
  • New Topic