matt matt - 5 months ago 7
Java Question

Find and delete specific objects from a Set with minimal iteration using Java

I have a set of objects and each object has its own id...

I also have a list of ids, each denoting the id of an object to be removed from the set..

Unfortunately I need the most efficient approach to do this... Obviously, I could iterate through the set, and for each entry iterate through the list to see if the ids match...

But is there a quicker way? I was wondering if it might be faster to use a Map to map ids to each object's placement within the set? It would be more to keep track of, but the efficiency here is the top priority - the set itself is dynamic and this operation will occur often...

The situation is essentially that I have a server thread that is closing sockets that another thread has determined are idle, and the server thread needs to get this done as quickly as possible, so it can resume its normal duties... Unfortunately the server thread is the only thread allowed to close sockets to avoid concurrency issues...

Are there better ways to do this?

Answer

I would go with @HovercraftFullOfEels' comment.

To expand a bit:

Replace your Set with a HashMap. Use the ID of the object as the key, and the object itself as the value. Then whenever you need to remove an object, it's a simple matter of

map.remove(id);

Generally speaking, any time you need random access to any form of Collection you're probably better off using some variation of Map instead (HashMap being the most common)