Which one is faster? List.contains() or Map.containsKey()

I later realized that I don’t really use the values contained in my Map so a List will suffice.

Map isn’t just a list of key-value pairs, it is a unique mapping from keys to values. So when you change from Map to List, you are allowing duplicates where you previously didn’t. On the other hand, a Set is exactly a Map without the values. So consider using a HashSet.

As for the search complexities:

list.contains is O(n), hashSet.contains is O(1), and treeSet.contains is O(log n).

For general information on now HashMap works, google for “hashtable”. For TreeMap, google for “binary tree” or similar. Wikipedia has good entries on these subjects.

Be careful, however, to avoid the class Hashtable. It’s an archaeological artefact in the modern library. For your case HashSet is probably the best choice.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)