I have a List<String> object that contains country names. How can I sort this list alphabetically?
16 Answers
Assuming that those are Strings, use the convenient static method sort:
Collections.sort(listOfCountryNames)
4 Comments
'Z' comes before 'a'. The question was about an alphabetical sort.Solution with Collections.sort
If you are forced to use this List, or if your program has a structure like
- Create a list
- Add some country names
- sort them once
- never change that list again
then Thilos answer is the best way to do it. Combine it with the advice from Tom Hawtin - tackline and you get
java.util.Collections.sort(listOfCountryNames, Collator.getInstance());
Solution with a TreeSet
If you have the choice, and if your application is likely to become more complex, you could modify your code to use a TreeSet instead. This kind of collection sorts your items as they are inserted. There is no need to call sort().
Collection<String> countryNames =
new TreeSet<String>(Collator.getInstance());
countryNames.add("UK");
countryNames.add("Germany");
countryNames.add("Australia");
// Voila... sorted.
Side note on why I prefer the TreeSet
It has some subtle but important advantages:
- It's just shorter. But only one line shorter.
- Never worry about is this list really sorted right now, because a TreeSet is always sorted, no matter what you do.
- You cannot have duplicate entries. Depending on your situation, this can be a pro or a con. If you need duplicates, stick to your list.
- An experienced programmer looks at
TreeSet<String> countyNamesand immediately knows: this is a sorted collection of strings without duplicates, and I can be sure that this is true at any moment. So much information in one short declaration. - A real performance gain in some cases. If you use a list, and you insert values very often, and the list may be read between those insertions, then you have to sort the list after each insertion. The set does the same thing, but much faster.
Using the right collection for the right task is a key to writing short and bug-free code. It's not so demonstrative in this case, because you're only saving one line. But I've lost count of how often I see someone using a list when they want to make sure there are no duplicates, and then building that functionality themselves. Or even worse, using two lists when you really need one map.
Don't get me wrong: Using Collections.sort is not a bug or a mistake. But there are many cases where the TreeSet is much cleaner.
9 Comments
Strings is lexicographic, not alphabetical. 'Z' comes before 'a', unlike an alphabetical sort.You can create a new sorted copy using Java 8 Stream or Guava:
// Java 8 version
List<String> sortedNames = names.stream().sorted().collect(Collectors.toList());
// Guava version
List<String> sortedNames = Ordering.natural().sortedCopy(names);
Another option is to sort in-place via Collections API:
Collections.sort(names);
1 Comment
Strings is lexicographic, not alphabetical. 'Z' comes before 'a', unlike an alphabetical sort.Better late than never! Here is how we can do it(for learning purpose only)-
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class SoftDrink {
String name;
String color;
int volume;
SoftDrink (String name, String color, int volume) {
this.name = name;
this.color = color;
this.volume = volume;
}
}
public class ListItemComparision {
public static void main (String...arg) {
List<SoftDrink> softDrinkList = new ArrayList<SoftDrink>() ;
softDrinkList .add(new SoftDrink("Faygo", "ColorOne", 4));
softDrinkList .add(new SoftDrink("Fanta", "ColorTwo", 3));
softDrinkList .add(new SoftDrink("Frooti", "ColorThree", 2));
softDrinkList .add(new SoftDrink("Freshie", "ColorFour", 1));
Collections.sort(softDrinkList, new Comparator() {
@Override
public int compare(Object softDrinkOne, Object softDrinkTwo) {
//use instanceof to verify the references are indeed of the type in question
return ((SoftDrink)softDrinkOne).name
.compareTo(((SoftDrink)softDrinkTwo).name);
}
});
for (SoftDrink sd : softDrinkList) {
System.out.println(sd.name + " - " + sd.color + " - " + sd.volume);
}
Collections.sort(softDrinkList, new Comparator() {
@Override
public int compare(Object softDrinkOne, Object softDrinkTwo) {
//comparision for primitive int uses compareTo of the wrapper Integer
return(new Integer(((SoftDrink)softDrinkOne).volume))
.compareTo(((SoftDrink)softDrinkTwo).volume);
}
});
for (SoftDrink sd : softDrinkList) {
System.out.println(sd.volume + " - " + sd.color + " - " + sd.name);
}
}
}
5 Comments
Strings is lexicographic, not alphabetical. 'Z' comes before 'a', unlike an alphabetical sort.In one line, using Java 8:
list.sort(Comparator.naturalOrder());
1 Comment
Comparator used with Strings is not alphabetical. 'Z' comes before 'a', unlike an alphabetical sort.Unless you are sorting strings in an accent-free English only, you probably want to use a Collator. It will correctly sort diacritical marks, can ignore case and other language-specific stuff:
Collections.sort(countries, Collator.getInstance(new Locale(languageCode)));
You can set the collator strength, see the javadoc.
Here is an example for Slovak where Š should go after S, but in UTF Š is somewhere after Z:
List<String> countries = Arrays.asList("Slovensko", "Švédsko", "Turecko");
Collections.sort(countries);
System.out.println(countries); // outputs [Slovensko, Turecko, Švédsko]
Collections.sort(countries, Collator.getInstance(new Locale("sk")));
System.out.println(countries); // outputs [Slovensko, Švédsko, Turecko]
Comments
Here is what you are looking for
listOfCountryNames.sort(String::compareToIgnoreCase)
1 Comment
By using Collections.sort(), we can sort a list.
public class EmployeeList {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> empNames= new ArrayList<String>();
empNames.add("sudheer");
empNames.add("kumar");
empNames.add("surendra");
empNames.add("kb");
if(!empNames.isEmpty()){
for(String emp:empNames){
System.out.println(emp);
}
Collections.sort(empNames);
System.out.println(empNames);
}
}
}
output:
sudheer
kumar
surendra
kb
[kb, kumar, sudheer, surendra]
2 Comments
Strings is lexicographic, not alphabetical. 'Z' comes before 'a', unlike an alphabetical sort.descending alphabet:
List<String> list;
...
Collections.sort(list);
Collections.reverse(list);
1 Comment
Java 8 ,
countries.sort((country1, country2) -> country1.compareTo(country2));
If String's compareTo is not suitable for your need, you can provide any other comparator.
Comments
public static void sortByAlphabetCountry(List<Employee> listCountry) {
listCountry.sort((o1, o2) -> {
return o1.getName().compareTo(o2.getName());
});
}
1 Comment
Same in JAVA 8 :-
//Assecnding order
listOfCountryNames.stream().sorted().forEach((x) -> System.out.println(x));
//Decending order
listOfCountryNames.stream().sorted((o1, o2) -> o2.compareTo(o1)).forEach((x) -> System.out.println(x));
1 Comment
Strings is lexicographic, not alphabetical. 'Z' comes before 'a', unlike an alphabetical sort.//Here is sorted List alphabetically with syncronized
package com.mnas.technology.automation.utility;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
/**
*
* @author manoj.kumar
*/
public class SynchronizedArrayList {
static Logger log = Logger.getLogger(SynchronizedArrayList.class.getName());
@SuppressWarnings("unchecked")
public static void main(String[] args) {
List<Employee> synchronizedList = Collections.synchronizedList(new ArrayList<Employee>());
synchronizedList.add(new Employee("Aditya"));
synchronizedList.add(new Employee("Siddharth"));
synchronizedList.add(new Employee("Manoj"));
Collections.sort(synchronizedList, new Comparator() {
public int compare(Object synchronizedListOne, Object synchronizedListTwo) {
//use instanceof to verify the references are indeed of the type in question
return ((Employee)synchronizedListOne).name
.compareTo(((Employee)synchronizedListTwo).name);
}
});
/*for( Employee sd : synchronizedList) {
log.info("Sorted Synchronized Array List..."+sd.name);
}*/
// when iterating over a synchronized list, we need to synchronize access to the synchronized list
synchronized (synchronizedList) {
Iterator<Employee> iterator = synchronizedList.iterator();
while (iterator.hasNext()) {
log.info("Sorted Synchronized Array List Items: " + iterator.next().name);
}
}
}
}
class Employee {
String name;
Employee (String name) {
this.name = name;
}
}
4 Comments
Strings is lexicographic, not alphabetical. 'Z' comes before 'a', unlike an alphabetical sort.