aspose file tools*
The moose likes Java in General and the fly likes Can I sort String arrays? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Can I sort String arrays?" Watch "Can I sort String arrays?" New topic
Author

Can I sort String arrays?

Ananth Chellathurai
Ranch Hand

Joined: Nov 21, 2007
Posts: 349

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


Ananth Chellathurai [Walk on software]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36464
    
  15
Yes, it is easy since String implements the Comparable interface; you can use s1.compareTo(s2).
Ananth Chellathurai
Ranch Hand

Joined: Nov 21, 2007
Posts: 349

So what should I compare to? I just want my string array to be sorted alphabetically.

Ananth
arulk pillai
Author
Ranch Hand

Joined: May 31, 2007
Posts: 3216



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 ]

Java Interview Questions and Answers Blog | Amazon.com profile | Java Interview Books
Ananth Chellathurai
Ranch Hand

Joined: Nov 21, 2007
Posts: 349

Thanks a lot Arul. I will use this in my implementation.

Ananth Chellathurai
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

You may want to use String.CASE_INSENSITIVE_ORDER if you want to sort it while ignoring the case.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can I sort String arrays?
 
Similar Threads
I am having trouble sorting an array of records that contains strings
Sorting an Array
Android
Manipulating Array Data
How to sort array of string