Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of Converting List<String> to HashSet<String> Java

So I have a list of strings that I need to instantiate once every time a service is called. Is it worth it to convert the List<String> to a HashSet<String> and then check if the String is in the hashSet?

eg.

HashSet<String> services = new HashSet<String>((List<String>) services);     

I know checking for the string in the list is O(n) and the check for the string in the hashSet is O(1). I think the conversion is probably O(n).

Is there a performance benefit to the recast if I am not searching over the list more than a few times?

like image 430
ford prefect Avatar asked Sep 16 '15 16:09

ford prefect


2 Answers

There is no benefit to switching. Your Bio O performance analysis is correct.

like image 70
Asaph Avatar answered Sep 21 '22 18:09

Asaph


List and Set are not the same thing:

  • A list is ordered. A set is not.
  • A list can contains the same object multiple times. The set don't allow duplications.

So the first questions you need to ask yourself are:

  • I need duplication in the list?
  • I need a special order in the list?

If the answer to both questions is no it is better to use an HashSet instead of the List. This will guarantee better performances retrieving elements.

If you can't change the List to an HashSet but you need to duplicate data structures it is necessary to check better your code to see if the set creation time is slower than the time gained for retrieving elements

like image 36
Davide Lorenzo MARINO Avatar answered Sep 21 '22 18:09

Davide Lorenzo MARINO