如何在Java中按其元素大小对ArrayList排序? [英] How to sort an ArrayList by its elements size in Java?
本文介绍了如何在Java中按其元素大小对ArrayList排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个List<String> L1 = new ArrayList<>()
,具有以下字符串作为元素:
So I have a List<String> L1 = new ArrayList<>()
with the following strings as elements:
- l,l,u,u.
- r,u,d,l,d,l,u.
- l,u,d,r,r,r,r,r,u,d.
- l,你.
- l,u,r.
如何按元素的大小对list
进行排序,以便在最终状态L1中应如下所示:
How do I sort the list
by its element's size so that in the final state L1 should be like this:
- l,你.
- l,u,r.
- l,l,u,u.
- r,u,d,l,d,l,u.
- l,u,d,r,r,r,r,r,u,d.
我尝试使用Collections.sort
,但是按字母顺序排序,这显然不是我想要的.
I have tried using Collections.sort
, but that sorts alphabetically, which is obviously not what I want.
推荐答案
I think what you are looking for is Collections.sort(java.util.List, java.util.Comparator). With it you can specify a custom Comparator
that compares the strings based on length instead of alphabetical relationship.
类似这样的东西:
List<String> stringList = new ArrayList<String>();
// Fill the list
Comparator<String> stringLengthComparator = new Comparator<String>()
{
@Override
public int compare(String o1, String o2)
{
return Integer.compare(o1.length(), o2.length());
}
};
Collections.sort(stringList, stringLengthComparator);
这篇关于如何在Java中按其元素大小对ArrayList排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文