Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move specific items to the end of a list

I have an ArrayList in Java:

{"deleteItem", "createitem", "exportitem", "deleteItems", "createItems"}

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.

like image 526
Or Smith Avatar asked Apr 07 '14 07:04

Or Smith


People also ask

How do you move an item to the end of a list in Python?

Method #1 : Using append() + pop() + index() This particular functionality can be performed in one line by combining these functions. The append function adds the element removed by pop function using the index provided by index function.

How do I remove last 10 items from a list in Python?

Use the del statement with list slicing to remove the last N elements from a list, e.g. del my_list[len(my_list) - n:] The del statement will remove the last N elements from the original list.


2 Answers

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);
like image 102
Kristjan Veskimäe Avatar answered Sep 22 '22 06:09

Kristjan Veskimäe


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.

like image 33
Pierre Rust Avatar answered Sep 19 '22 06:09

Pierre Rust