Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: How to sort alphabetically?

  1. #1
    Member
    Join Date
    Feb 2011
    Posts
    30
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default How to sort alphabetically?

    If I have a list of strings within an array, say:
    [0] = jones
    [1] = apple
    [2] = struggle
    [3] = zebra

    How can I alphabetize them and place them into another array, in correct alphabetical order?


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: How to sort alphabetically?

    See Arrays (Java Platform SE 6) sort methods

  3. #3
    Junior Member
    Join Date
    Jul 2011
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: How to sort alphabetically?

    Hey,

    You should look into the method "compareTo(String s)" for Strings. The result is negative if the first String being compared is "more" alphabetical than the parameter. Conversely, it will return positive if the first string being compared is "less" alphabetical.

    For example

     
    public class StringsCompareTo {
     
    	public static void main(String[] args){
     
    		String apple = "Apple";
    		String zebra = "Zebra";
     
    		System.out.println(apple.compareTo(zebra));     //Outputs negative number
    		System.out.println(zebra.compareTo(apple));     //Outputs positive number
     
     
    	}
     
    }

    Hope that helped!

Similar Threads

  1. Bubble Sort help
    By baueml01 in forum What's Wrong With My Code?
    Replies: 9
    Last Post: June 5th, 2011, 08:47 PM
  2. Arrays.Sort Help
    By Brandon Seale in forum What's Wrong With My Code?
    Replies: 5
    Last Post: February 20th, 2011, 02:32 AM
  3. Timing a sort
    By joshft91 in forum Collections and Generics
    Replies: 1
    Last Post: February 7th, 2011, 05:12 PM
  4. Insertion Sort
    By Kimimaru in forum Algorithms & Recursion
    Replies: 2
    Last Post: December 6th, 2010, 06:26 AM
  5. bubble sort and selection sort on strings
    By Sir Saula in forum What's Wrong With My Code?
    Replies: 5
    Last Post: July 3rd, 2010, 09:44 AM