How to delete a specific List object in Java?

I have a list of approximately 100,000 Java employees. Now I want to quickly remove a specific employee object from the list. What are the possible ways to do this without repeating the whole list? (If I repeat each object, compare the details and then delete: this script takes a lot of time)

+7
java list
source share
2 answers

You need to quickly find the object. You could

  • sorting an ArrayList and then doing a binary search using Collections.binarySearch O(log N) Note. Actually removing an element from ArrayList O(n) . Although LinkedList is like O(1) for deletion, a binary search on it would be pointless i.e. much slower than O(n)
  • you may have an Employee hash set and the deletion will be O(1) amortized. You can use LinkedHashSet if you want to keep some order, for example, the insertion order.
  • you can make the object mutable and have a field of type enabled that you set to false instead of actually deleting it. You can delete it later as a batch job for some time (overnight or on weekends).
+7
source share

Now I want to remove a specific employee object from the list ...

You can just use List.remove for this

... fast

In practice, even when you delete an item, there can be an O(1) operation, iteration along the entire length of the O(n) list and, as you suspected, not very fast.

I feel that your problem is better served by the power of a hash map. This is a constant search and delete time. The LinkedHashMap class can meet your needs. It maintains the insertion order in the same way as the linked list, but also has constant insertion and deletion of time.

+2
source share

All Articles