我有一个包含国家名称的List<String>对象。我如何按字母顺序对这个列表排序?
使用Collections.sort解决方案
如果您被迫使用该List,或者如果您的程序具有类似的结构
创建列表 添加一些国家名称 对它们排序一次 不要再更改这个列表
那么这个答案将是最好的方法。如果你结合Tom Hawtin - tackline的建议,你会得到:
java.util.Collections.sort(listOfCountryNames, Collator.getInstance());
树集的解决方案
如果您可以自由决定,并且您的应用程序可能变得更加复杂,那么您可以更改代码以使用TreeSet。这种集合在插入条目时对它们进行排序。不需要调用sort()。
Collection<String> countryNames =
new TreeSet<String>(Collator.getInstance());
countryNames.add("UK");
countryNames.add("Germany");
countryNames.add("Australia");
// Tada... sorted.
旁注为什么我更喜欢树集
这有一些微妙但重要的优势:
It's simply shorter. Only one line shorter, though. Never worry about is this list really sorted right now becaude a TreeSet is always sorted, no matter what you do. You cannot have duplicate entries. Depending on your situation this may be a pro or a con. If you need duplicates, stick to your List. An experienced programmer looks at TreeSet<String> countyNames and instantly knows: this is a sorted collection of Strings without duplicates, and I can be sure that this is true at every moment. So much information in a short declaration. Real performance win in some cases. If you use a List, and insert values very often, and the list may be read between those insertions, then you have to sort the list after every insertion. The set does the same, but does it much faster.
为正确的任务使用正确的集合是编写简短且没有错误的代码的关键。在这种情况下,它不是指示性的,因为你只保存了一行。但是我已经不再计算当有人想要确保没有重复时使用List的频率,然后他们自己构建该功能。或者更糟糕的是,在真正需要Map时使用两个list。
不要误解我的意思:使用集合。排序不是错误或缺陷。但是在很多情况下,TreeSet要干净得多。
使用Collections.sort的两个参数。你会想要一个合适的比较器,处理大小写适当(即词法,而不是UTF16排序),比如通过java.text.Collator.getInstance获得。
您可以使用Java 8 Stream或Guava创建一个新的排序副本:
// Java 8 version
List<String> sortedNames = names.stream().sorted().collect(Collectors.toList());
// Guava version
List<String> sortedNames = Ordering.natural().sortedCopy(names);
另一种选择是通过Collections API就地排序:
Collections.sort(names);
迟到总比不到好!以下是我们如何做(仅供学习之用)
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);
}
}
}
//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;
}
}
除非您只使用无重音的英文对字符串进行排序,否则您可能希望使用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(),我们可以对列表进行排序。
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]
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));
你可以使用下面这行
集合。排序(listOfCountryNames String.CASE_INSENSITIVE_ORDER)
它类似于Thilo的建议,但不会区分大小写字符。
Java 8,
countries.sort((country1, country2) -> country1.compareTo(country2));
如果String的compareTo不适合您的需要,您可以提供任何其他比较器。
推荐文章
- 映射enum在JPA与固定的值?
- 如何找到可用的端口?
- 假唤醒在Java中真的发生了吗?
- 如何按字母顺序排序列表?
- 如何在java中格式化持续时间?(如格式H:MM:SS)
- urlencoder .encode(字符串)已弃用,我应该使用什么代替?
- javax.transaction.Transactional vs . org.springframework.transaction.annotation.Transactional
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何读一个文本文件到一个列表或数组与Python
- Linq选择列表中存在的对象(A,B,C)
- 如何找到Java堆大小和内存使用(Linux)?
- 返回大列表中每n项的python方式
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?