Search code examples
javasortingarraylistnamesalphabetical

How to sort an arrayList using compareTo


As the user is inputting names, I want the names to sort out instantly using a compareTo method and return them in alphabetical order as the user is entering the names.

I've tried using a forLoop method but don't understand exactly how the compareTo method actually works, I've looked everywhere and can't find exactly how to complete it.

public class sortNames
{
public static void main(String[] args)
{
    Scanner UI = new Scanner(System.in);
    ArrayList<String> names = new ArrayList<String>();
    System.out.println("Enter words, stop with -1");
    while (true)
    {
        String input = UI.next();
        if(!input.equals("-1"))
        {
            names.add(input);
            System.out.println(names);
        }
        else
        {
            break;
        }
    }
 }
}

I would want the output to look something like this (User enters) "Bob" (should return) [Bob] (User enters) "Ally" (should return) [Ally, Bob] and so on with other names.


Solution

  • Just use ArrayList's method sort :

    names.sort(null);
    

    The null parameter indicates that the natural ordering (compareTo) should be used.