我有一个包含国家名称的List<String>对象。我如何按字母顺序对这个列表排序?


当前回答

下行字母:

List<String> list;
...
Collections.sort(list);
Collections.reverse(list);

其他回答

Java 8,

countries.sort((country1, country2) -> country1.compareTo(country2));

如果String的compareTo不适合您的需要,您可以提供任何其他比较器。

除非您只使用无重音的英文对字符串进行排序,否则您可能希望使用Collator。它将正确排序变音符符号,可以忽略大小写和其他特定于语言的东西:

Collections.sort(countries, Collator.getInstance(new Locale(languageCode)));

你可以设置排序器的强度,参见javadoc。

下面是一个斯洛伐克语的例子,Š应该在S后面,但在UTF中Š应该在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]

使用Collections.sort的两个参数。你会想要一个合适的比较器,处理大小写适当(即词法,而不是UTF16排序),比如通过java.text.Collator.getInstance获得。

//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;

}
}

这是你要找的东西

listOfCountryNames.sort(String::compareToIgnoreCase)