antz
antz

Reputation: 1071

How can I sort an ArrayList of Strings in Java?

I have Strings that are put into an ArrayList randomly.

private ArrayList<String> teamsName = new ArrayList<String>();
String[] helper; 

For example:

teamsName.add(helper[0]) where helper[0] = "dragon";   
teamsName.add(helper[1]) where helper[1] = "zebra";   
teamsName.add(helper[2]) where helper[2] = "tigers" // and so forth up to about 150 strings.

Given the fact that you cannot control the inputs (i.e. string that is coming into the ArrayList is random; zebra or dragon in any order), once the ArrayListis filled with inputs, how do I sort them alphabetically excluding the first one?

teamsName[0] is fine; sort teamsName[1 to teamsName.size] alphabetically.

Upvotes: 37

Views: 125081

Answers (5)

katsu
katsu

Reputation: 566

You can use TreeSet that automatically order list values:

import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {
        System.out.println("Tree Set Example!\n");

        TreeSet <String>tree = new TreeSet<String>();
        tree.add("aaa");
        tree.add("acbbb");
        tree.add("aab");
        tree.add("c");
        tree.add("a");

        Iterator iterator;
        iterator = tree.iterator();

        System.out.print("Tree set data: ");

        //Displaying the Tree set data
        while (iterator.hasNext()){
            System.out.print(iterator.next() + " ");
        }
    }

}

I lastly add 'a' but last element must be 'c'.

Upvotes: 3

petrsyn
petrsyn

Reputation: 5116

You might sort the helper[] array directly:

java.util.Arrays.sort(helper, 1, helper.length);

Sorts the array from index 1 to the end. Leaves the first item at index 0 untouched.

See Arrays.sort(Object[] a, int fromIndex, int toIndex)

Upvotes: 5

Rohit Jain
Rohit Jain

Reputation: 213401

Check Collections#sort method. This automatically sorts your list according to natural ordering. You can apply this method on each sublist you obtain using List#subList method.

private List<String> teamsName = new ArrayList<String>();
List<String> subList = teamsName.subList(1, teamsName.size());
Collections.sort(subList);

Upvotes: 12

Juvanis
Juvanis

Reputation: 25950

Collections.sort(teamsName.subList(1, teamsName.size()));

The code above will reflect the actual sublist of your original list sorted.

Upvotes: 44

npinti
npinti

Reputation: 52205

Take a look at the Collections.sort(List<T> list).

You can simply remove the first element, sort the list and then add it back again.

Upvotes: 6

Related Questions