Java 如何按字母顺序对列表进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/708698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I sort a List alphabetically?
提问by Lennie
I have a List<String>
object that contains country names. How can I sort this list alphabetically?
我有一个List<String>
包含国家名称的对象。如何按字母顺序对这个列表进行排序?
回答by Thilo
回答by Lena Schimmel
Solution with Collections.sort
使用 Collections.sort 的解决方案
If you are forced to use that List, or if your program has a structure like
如果您被迫使用该列表,或者您的程序具有类似的结构
- Create List
- Add some country names
- sort them once
- never change that list again
- 创建列表
- 添加一些国家名称
- 对它们进行一次排序
- 永远不要再更改该列表
then Thilos answer will be the best way to do it. If you combine it with the advice from Tom Hawtin - tackline, you get:
那么 Thilos 的回答将是最好的方法。如果你把它和Tom Hawtin的建议结合起来——tackline,你会得到:
java.util.Collections.sort(listOfCountryNames, Collator.getInstance());
Solution with a TreeSet
使用 TreeSet 的解决方案
If you are free to decide, and if your application might get more complex, then you might change your code to use a TreeSet instead. This kind of collection sorts your entries just when they are inserted. No need to call sort().
如果您可以自由决定,并且您的应用程序可能变得更复杂,那么您可以更改代码以使用 TreeSet。这种集合会在您的条目插入时对其进行排序。无需调用 sort()。
Collection<String> countryNames =
new TreeSet<String>(Collator.getInstance());
countryNames.add("UK");
countryNames.add("Germany");
countryNames.add("Australia");
// Tada... sorted.
Side note on why I prefer the TreeSet
关于为什么我更喜欢 TreeSet 的旁注
This has some subtle, but important advantages:
这有一些微妙但重要的优点:
- It's simply shorter. Only one line shorter, though.
- Never worry about is this list really sorted right nowbecaude 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.
- 它只是更短。不过只短了一行。
- 永远不要担心这个列表现在真的排序了,因为无论你做什么,TreeSet 总是排序的。
- 您不能有重复的条目。根据您的情况,这可能是优点或缺点。如果您需要重复,请坚持您的列表。
- 有经验的程序员一看就
TreeSet<String> countyNames
知道:这是一个有序的字符串集合,没有重复,我可以肯定这在每一刻都是正确的。一个简短的声明中有这么多信息。 - 在某些情况下,真正的性能取胜。如果您使用列表,并且经常插入值,并且可能会在这些插入之间读取列表,那么您必须在每次插入后对列表进行排序。该集合执行相同的操作,但执行速度要快得多。
Using the right collection for the right task is a key to write short and bug free code. It's not as demonstrative in this case, because you just save one line. But I've stopped counting how often I see someone using a List when they want to ensure there are no duplictes, and then build that functionality themselves. Or even worse, using two Lists when you really need a Map.
为正确的任务使用正确的集合是编写简短且无错误代码的关键。在这种情况下,它不那么具有示范性,因为您只需保存一行。但是我已经停止计算我看到有人使用 List 的频率,因为他们想要确保没有重复,然后自己构建该功能。或者更糟的是,当你真的需要一个 Map 时使用两个 Lists。
Don't get me wrong: Using Collections.sort is not an error or a flaw. But there are many cases when the TreeSet is much cleaner.
不要误会我的意思:使用 Collections.sort 不是错误或缺陷。但是在很多情况下 TreeSet 更干净。
回答by Tom Hawtin - tackline
Use the two argument for of Collections.sort
. You will want a suitable Comparator
that treats case appropriate (i.e. does lexical, not UTF16 ordering), such as that obtainable through java.text.Collator.getInstance
.
使用 of 的两个参数Collections.sort
。您将需要一个合适的Comparator
,可以适当地处理大小写(即进行词法排序,而不是 UTF16 排序),例如可通过java.text.Collator.getInstance
.
回答by Doout
You can try using a method that I made.
您可以尝试使用我制作的方法。
String key
- will be the order you want and in this case in alphabetically. Just put "abc...".
String key
- 将是您想要的顺序,在这种情况下按字母顺序排列。只需输入“abc...”。
String list[]
- the list you want to put in order using key.
String list[]
- 要使用键排列的列表。
int index
- set as 0, will set the offset for the key.
int index
- 设置为 0,将设置键的偏移量。
public static String[] order(String key, String list[], int index) {
ArrayList<String> order_List = new ArrayList<String>();
ArrayList<String> temp_Order_List = null;
char[] key_char = key.toCharArray();
for (int offset = 0; offset < key_char.length; offset++) {
if (key_char.length >= offset + index) {
String str = (index > 1 ? list[0].substring(0, index - 1) : "")
+ new String(key_char, offset, 1);
for (int i = 0; i < list.length; i++) {
temp_Order_List = new ArrayList<String>();
for (int k = 0; k < list.length; k++) {
if (!order_List.contains(list[k])
&& !temp_Order_List.contains(list[k])) {
if (list[k].equalsIgnoreCase(str))
order_List.add(list[k]);
else if (list[k].toLowerCase().startsWith(str.toLowerCase())) {
temp_Order_List.add(list[k]);
}
}
}
if (temp_Order_List.size() > 0) {
if (temp_Order_List.size() > 1) {
String[] add = order(key,
temp_Order_List.toArray(new String[temp_Order_List
.size()]), index + 1);
for (String s : add) {
order_List.add(s);
}
} else {
order_List.add(temp_Order_List.get(0));
}
}
}
}
}
return order_List.toArray(new String[order_List.size()]);
}
回答by Vitalii Fedorenko
You can create a new sorted copy using Java 8 Stream or Guava:
您可以使用 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);
Another option is to sort in-place via Collections API:
另一种选择是通过 Collections API 就地排序:
Collections.sort(names);
回答by Tirath
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);
}
}
}
回答by Tirath
//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;
}
}
回答by Oliv
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:
除非您仅使用无重音的英语对字符串进行排序,否则您可能希望使用Collator
. 它将正确排序变音符号,可以忽略大小写和其他特定于语言的内容:
Collections.sort(countries, Collator.getInstance(new Locale(languageCode)));
You can set the collator strength, see the javadoc.
您可以设置collator strength,请参阅 javadoc。
Here is an example for Slovak where ?
should go after S
, but in UTF ?
is somewhere after Z
:
以下是斯洛伐克语的示例,?
应该在 之后的位置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]
回答by ASR
By using Collections.sort()
, we can sort a list.
通过使用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);
}
}
}
output:
输出:
sudheer
kumar
surendra
kb
[kb, kumar, sudheer, surendra]
回答by prashant
Here is what you are looking for
这就是你要找的
listOfCountryNames.sort(String::compareToIgnoreCase)