将特定项目移动到列表末尾 [英] 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屋!
查看全文