Move specific items to the end of a list

巧了我就是萌 提交于 2019-12-05 06:27:07
Kristjan Veskimäe

Use custom Comparator:

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);

If you want something efficient and need to remove elements in the beginning and middle of a List I would suggest using a LinkedList instead of a array list. That would avoid rewriting the underlying array for each remove operation.

Then, you simply iterate on the list, calling remove and addLast for any string that contains delete.

Of course, this is only OK if there is nothing preventing you from replacing your ArrayList with a LinkedList.

You only want to put the elements with delete at the end of the list so ordering is O(nlogn) while we could do this in one pass, in O(n) (although using a new list). We could create a new LinkedLIst and pass through the original list adding the elements with "delete" at the end and the others at the begginging.

    LinkedList<String> orderedList = new LinkedList<>();
    for(String e:originalList){
        if (e.indexOf("delete")>=0) {
            orderedList.addLast(e);
        } else {
            orderedList.addFirst(e);
        }
    }

This is faster than sorting.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!