Basically I have about 1,000,000 strings, for each request I have to check if a String belongs to the list or not.
I'm worried about the performance, so what's the best method? ArrayList
? Hash?
Basically I have about 1,000,000 strings, for each request I have to check if a String belongs to the list or not.
I'm worried about the performance, so what's the best method? ArrayList
? Hash?
Sometimes you want to check if an object is in the list/set and at the same time you want the list/set to be ordered. If you are looking to also retrieve objects easily without using an enumeration or iterator, you may consider using both an
ArrayList<String>
andHashMap<String, Integer>
. The list is backed by the map.Example from some work I recently did:
In this case, parameter
K
would be aString
for you. The map (childrenToMapList
) storesStrings
inserted into the list (children
) as the key, and the map values are the index position in the list.The reason for the list and the map is so that you can retrieve indexed values of the list, without having to do an iteration over a
HashSet<String>
.Your best bet is to use a
HashSet
and check if a string exists in the set via thecontains()
method. HashSets are built for fast access via the use of Object methodshashCode()
andequals()
. The Javadoc forHashSet
states:HashSet stores objects in hash buckets which is to say that the value returned by the
hashCode
method will determine which bucket an object is stored in. This way, the amount of equality checks theHashSet
has to perform via theequals()
method is reduced to just the other Objects in the same hash bucket.To use HashSets and HashMaps effectively, you must conform to the
equals
andhashCode
contract outlined in the javadoc. In the case ofjava.lang.String
these methods have already been implemented to do this.If you are having such a large amount of strings, the best opportunity for you is to use a database. Look for MySQL.
With such a huge number of Strings, I immediately think of a Trie. It works better with a more limited set of characters (such as letters) and/or when the start of many string overlap.
Not only for String, you can use Set for any case you need unique items.
If the type of items is primitive or wrapper, you may not care. But if it is a class, you must override two methods:
I'd use a
Set
, in most casesHashSet
is fine.