将特定项目移到列表末尾 [英] Move specific items to the end of a list
本文介绍了将特定项目移到列表末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Java
中有一个ArrayList
:
{"deleteItem", "createitem", "exportitem", "deleteItems", "createItems"}
我想将所有包含delete
的字符串移到列表的末尾,所以我将得到下一个:
I want to move all string which contains delete
to the end of the list, so I would get the next:
{"createitem", "exportitem", "createItems", "deleteItem", "deleteItems"}`
我可以创建两个子列表-一个用于包含删除"单词的单词,另一个用于其他单词,然后将它们合并,但是我寻求一种更有效的方法.
I can create two sublists - one for the words which contain the 'delete' word, and one for the others, and then merge them, but I search for a more efficient way.
推荐答案
使用自定义比较器:
List<String> strings = Arrays.asList(
"deleteItem", "createitem", "exportitem", "deleteItems", "createItems"
);
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(final String o1, final String o2) {
if (o1.contains("delete") && !o2.contains("delete")) {
return 1;
}else if (!o1.contains("delete") && o2.contains("delete")) {
return -1;
}
return 0;
}
};
Collections.sort(strings, comparator);
System.out.println(strings);
这篇关于将特定项目移到列表末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文