← All benchmarksJava

Java ArrayList.contains vs HashSet.contains: 1,762 ms vs 0.25 ms

Is HashSet.contains faster than ArrayList.contains in Java?

Yes. In a test of 10,000 lookups in a collection of 100,000 integers on JDK 17, ArrayList.contains took 1,762 ms and HashSet.contains took 0.25 ms, because a list scans elements one by one while a hash set jumps straight to the bucket.

Results

ArrayList.contains (10,000 lookups)1,762 ms
HashSet.contains (10,000 lookups)0.25 ms

How it was measured

100,000 Integers in an ArrayList and a HashSet. 10,000 lookups for values near the end of the list (the slow case for a list). Best of 5 rounds after warm-up.

list.contains(x);   // O(n)
set.contains(x);    // O(1) average

Why

ArrayList.contains is O(n): it compares against each element until it finds a match. HashSet.contains hashes the value and checks one bucket, O(1) on average.

When this does not apply

For lists of a few dozen items the difference is negligible, and a Set loses ordering and duplicates. Searching near the start of the list also hides the gap.

Environment

MacBook Air (Apple silicon, 8 cores), macOS, JDK 17. Measured 2026-10-12.

Source: shorts/demo-ticket/java/Lookup.java in my content-engine repository. Treat any single run as a direction; re-run it on your hardware.

FAQ

When should I use a Set instead of a List in Java?
When you test membership repeatedly (for example inside a loop) and do not need order or duplicates.
Is HashSet always faster?
For repeated lookups on large collections, yes. For tiny collections the difference is below measurement noise.

Related

By Josué Barros, senior software engineer (full-stack, data and AI).