0

consider I have an array list like : [2,5,1,8,6] and I want to remove all elements from 1 till the end .and the arraylist will be like :[2,5] how can i do this? thanks

5 Answers 5

3

It is worth noting that you cannot add/remove from an Arrays.asList(), but you can do.

List<Integer> list = Arrays.asList(2, 5, 1, 8, 6);
int idx = list.indexOf(1);
if (idx>=0) list = list.subList(0, idx);
Sign up to request clarification or add additional context in comments.

Comments

3
List<Integer> list = Arrays.asList(2, 5, 1, 8, 6);
boolean remove = false;
Iterator<Integer> it = list.iterator();
while (it.hasNext() {
   if (!remove && it.next() == 1) {
      remove = true;
   }
   if (remove) {
      it.remove();
   }
}

Comments

0
list = list.subList(0, 1);

Comments

0

The most efficient way to remove elements from ArrayList is to remove them from the end of the list. Each element you remove from the middle of the list will result in all the latter elements being moved to the left. If the list is large, this can result in a significant performance issue.

However, in your case, you might be better off just creating a new sublist with the remaining two elements.

Comments

0

Another way of doing it would be to simply pop items off the end of the List until we have popped the starting element. Each item can be popped in O(1) time, so the entire operation is O(n).

class Main{
    private static List<Integer> inputs = new ArrayList<Integer>();

    public static void main(String args[]){
        for (int x: new int[]{2,5,1,8,6})
            inputs.add(x);
        System.out.println(inputs);
        int start=inputs.indexOf(1);
        if (start>=0){ //check if there is a 1 in input
            while (inputs.size()>start)
                inputs.remove(inputs.size()-1);
        }
        System.out.println(inputs);

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.