Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete particular List object in Java? [closed]

Tags:

java

list

I have a list of around 100,000 employees in Java. Now I want to delete a particular employee object from list quickly. What are the possible ways to do it without iterating the whole list? (If I iterate each object, compare the details then delete: this scenario takes lot of time)

like image 962
ShaileshB Avatar asked Jun 27 '16 11:06

ShaileshB


2 Answers

You need a means of find the object quickly. You could

  • have an ArrayList sorted and then perform a binary search with Collections.binarySearch O(log N) Note: actually removing an element from an ArrayList is O(n) While LinkedList as O(1) for remove, a binary search on it would be pointless i.e. much slower than O(N)
  • you could have a hash Set of Employee instead and removal would be O(1) amortised. You could use a LinkedHashSet if you would like to preserve some order such as order of insertion.
  • you could make the object mutable and have a field like enabled which you set to false instead of actually removing it. You could remove it later as a batch job at some time (overnight or on the weekend)
like image 67
Peter Lawrey Avatar answered Nov 03 '22 02:11

Peter Lawrey


Now I want to delete a particular employee object from list ...

You can just use List.remove to do this

... quickly

In practice, even though removing the item might be an O(1) operation, iterating over the full length of the list is O(n), and is, as you susepcted, not very fast.

I feel that your problem would better be served by the power of a hashmap. This has constant lookup and removal time. The LinkedHashMap class might suit your needs. It maintains insertion order the same way a linked list does, but it also has constant time insertion and deletion.

like image 38
Tim Biegeleisen Avatar answered Nov 03 '22 01:11

Tim Biegeleisen