File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes arranging Strings in alphabetical order Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "arranging Strings in alphabetical order" Watch "arranging Strings in alphabetical order" New topic

arranging Strings in alphabetical order

Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
I want to arrange some Strings in alphabetical order. Do I have to write a program that looks something like this:

String a;
String b;
if (a.charAt(0) > b.charAt(0)){

// more code here


Well, that is a very rough draft. What I mean is, do I have to write a method that compares all the chars of the Strings to each other, or is there some method in Java.Lang or Java.Util that does that?
Rob Spoor

Joined: Oct 27, 2005
Posts: 20048

String implements the Comparable interface, so you can use that to compare. Alternatively, it also has a compareToIgnoreCase method that allows you to compare regardless of the case:

How To Ask Questions How To Answer Questions
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Additionally you can use the sort methods, java.util.Collections.sort() and java.util.Arrays.sort(). These rely on having either a Comparable or a Comparator. String is already a Comparable, but if you want a different sort order you can make a Comparator instead.

"I'm not back." - Bill Harding, Twister
Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
Thank you.
I agree. Here's the link:
subject: arranging Strings in alphabetical order
It's not a secret anymore!