有人可以建议一种方法来按顺序排列以下对象arraylist吗?
List<Object> = {/ele1/*,/ele1/subele1/*,/ele2/subele2/*,/ele2/*,/ele3/subele2/*,/ele3/*}
我需要输出
{/ele1/*,/ele2/*,/ele3/*,/ele1/subele1/*,/ele2/subele2/*,/ele3/subele2/*}
这可以实现使用元素长度吗?
答案 0 :(得分:1)
您需要提供一个自定义比较器,用于对使用元素长度作为比较的项目进行排序,如下所示:
public static void main(String[] args) throws Exception {
List<String> items = Arrays.asList("/ele1/*", "/ele1/subele1/*" ,"/ele2/subele2/*", "/ele2/*");
Collections.sort(items, new MinLengthComparator());
System.out.println(items);
}
private static class MinLengthComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
}