Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 585
antz Avatar asked Oct 24 '12 09:10

antz


People also ask

How would you sort a list of strings in Java?

Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.

How can we sort elements of ArrayList in Java?

In order to sort elements in an ArrayList in Java, we use the Collections. sort() method in Java. This method sorts the elements available in the particular list of the Collection class in ascending order. where list is an object on which sorting needs to be performed.

Can you sort strings in Java?

Strings in Java can be sorted using various methods such as: Arrays. sort() sorted() method (Java 8 Streams)

How do you sort strings?

Using the toCharArray() method Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array.


2 Answers

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

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

like image 109
Juvanis Avatar answered Oct 10 '22 10:10

Juvanis


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); 
like image 28
Rohit Jain Avatar answered Oct 10 '22 08:10

Rohit Jain