[英]Sorting ArrayList by sting length in java
I have an ArrayList我有一个 ArrayList
ArrayList<String[]> matches = new ArrayList<String[]>();
Collections.sort(matches, new Comparator<String>() {
@Override
public int compare(String word1, String word2) {
return word2.length() - word1.length();
}
});
I want to sort this ArrayList by the length of the strings in the ArrayList.我想按 ArrayList 中字符串的长度对这个 ArrayList 进行排序。 I want the list to be in descending order.
我希望列表按降序排列。
Input = ace, a, apple, cord
Output = apple, cord, ace, a
这适用于 Java 8。
Collections.sort(dictionary, (a, b)->Integer.compare(a.length(), b.length()));
you need to implement a comparator, like that:您需要实现一个比较器,如下所示:
class stringLengthComparator implements Comparator<String> {
public int compare(String o1, String o2) {
if (o1.length() > o2.length()) {
return 1;
} else if (o1.length() < o2.length()) {
return -1;
} else {
return 0;
}
}
}
and then you just sort your ArrayList like that:然后你只需像这样对你的 ArrayList 进行排序:
Collections.sort(matches, new stringLengthComparator());
You probably meant List<String>
, not List<String[]>
as the input.您可能指的是
List<String>
,而不是List<String[]>
作为输入。
In order to sort your list you need to use java.util.Collections.sort
method with custom comparator that compares elements by length:为了对列表进行排序,您需要使用
java.util.Collections.sort
方法和自定义比较器,按长度比较元素:
List<String> list = Arrays.asList( "ace", "a", "apple", "cord" ); Collections.sort(list, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o2.length() - o1.length(); } }); System.out.println(list);
This is exactly, how you are going to do your program using ArrayList.这正是您将如何使用 ArrayList 执行程序的方式。 Make sure you import the proper java.util classes.
确保导入正确的 java.util 类。
public static void main(String args[])
{
String matches[] = {"ace", "a", "apple", "cord"};
List<String> list = new ArrayList<String>();
Collections.addAll(list, matches);
Collections.sort(list, new Comparator<String>(){
public int compare(String o1, String o2)
{
return o1.length() - o2.length();
}
});
Collections.reverse(list);
System.out.println(list);
}
Input: "ace", "a", "apple", "cord"
Output: [apple, cord, ace, a]
PS This has been tested and it works exactly the way you want. PS 这已经过测试,它完全按照您想要的方式工作。
Since Java 8 you can directly use the method List.sort()
:从 Java 8 开始,您可以直接使用
List.sort()
方法:
List<String> stringList = Arrays.asList("ace", "a", "apple", "cord");
stringList.sort(Comparator.comparingInt(String::length).reversed());
stringList
will be ordered in descending order: stringList
将按降序排列:
apple, cord, ace, a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.