我有一个包含国家名称的 List<String>
对象,如何按字母顺序对此列表进行排序?
我有一个包含国家名称的 List<String>
对象,如何按字母顺序对此列表进行排序?
Collections.sort()
,我们可以对列表进行排序。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);
}
}
}
输出:
sudheer
kumar
surendra
kb
[kb, kumar, sudheer, surendra]
降序字母表:
List<String> list;
...
Collections.sort(list);
Collections.reverse(list);
countries.sort((country1, country2) -> country1.compareTo(country2));
public static void sortByAlphabetCountry(List<Employee> listCountry) {
listCountry.sort((o1, o2) -> {
return o1.getName().compareTo(o2.getName());
});
}
在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));
String
的默认排序是字典排序,而不是按字母顺序排序。 'Z'
在字典排序中排在'a'
之前,与按字母顺序排序不同。 - Chai T. Rex//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;
}
}
String
的默认排序是按字典顺序而非按字母表顺序。'Z'
在字典排序中排在 'a'
之前,与字母表排序不同。 - Chai T. Rex
String
默认使用的排序方式是字典排序,而不是按字母顺序排序。'Z'
在字典排序中排在'a'
之前,与按字母顺序排序不同。 - Chai T. Rex