谁能建议一种以降序排列以下对象arraylist的方法?
List<Object> = {/ele1/*,/ele1/subele1/*,/ele2/subele2/*,/ele2/*,/ele3/subele2/*,/ele3/*}
我需要输出为
{/ele1/*,/ele2/*,/ele3/*,/ele1/subele1/*,/ele2/subele2/*,/ele3/subele2/*}
使用元素长度是否可以实现?
您需要提供一个自定义比较器来对项目进行排序,该比较器使用元素长度作为比较,如下所示:
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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句