-6

I have an array list of 100 000 objects. I want to remove some of the objects which have a particular ID. I'm using for loop to search through the ArrayList and remove each of them. Hence it is very much time-consuming. Is there any possible way to do this without any looping?

James Z
  • 12,209
  • 10
  • 24
  • 44

3 Answers3

8
List<Type> list = ...
list.removeIf(item -> item.getId() == something);

As the name suggests, removeIf() removes all elements if they satisfy the predicate.

cameron1024
  • 9,083
  • 2
  • 16
  • 36
1

Since I don't know the structure of your Lakh class, I can only provide an example using Strings:

public static void main(String args[]) throws Exception {
    List<String> words = new ArrayList<>();

    words.add("I");
    words.add("want");
    words.add("to");
    words.add("remove");
    words.add("things");
    words.add("without");
    words.add("a");
    words.add("loop");

    System.out.println("———— BEFORE ————");
    words.forEach(word -> System.out.println(word));

    System.out.println("———— AFTER ————");
    // this is the removal action, it removes all entries that equal certain words
    words.removeIf(word -> word.equals("loop") || word.equals("remove"));

    words.forEach(word -> System.out.println(word));
}

Please not that this will use a loop under the hood, too. More precise:
An Iterator<E> in a while loop.

deHaar
  • 17,687
  • 10
  • 38
  • 51
  • @Adrian thanks, I wasn't able to extract that from the context *1 Lakh objects* but it's beginning to make sense ;-) – deHaar Aug 05 '19 at 12:17
  • 2
    The `default` implementation of `removeIf` uses an iterator based loop, but `ArrayList` overrides this method with a far better implementation, suited to the `ArrayList`. – Holger Aug 05 '19 at 13:24
-2

You can use remove() method like below:

List<String> nameList = ArrayList<String>();
nameList.add("Sam");
nameList.add("Sarah");

//Remove by index
nameList.remove(0);

//Remove by value
nameList.remove("Sarah");