Java
List Comparison
String List
Coding Tips
Duplicate Handling

How to compare two ListString to each other?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Comparing two List<String> objects in Java can mean different things depending on order and duplicate rules. Sometimes you need exact sequence equality. Other times, order should not matter, but duplicate counts still should. If you choose the wrong comparison strategy, tests may pass while business logic is wrong in production. The key is to state comparison semantics first, then use the corresponding API or algorithm. This article covers common list comparison modes, provides implementation examples, and explains how to keep comparisons readable and efficient.

Core Sections

Exact equality: same items, same order

Use List.equals when both content and order must match.

java
1List<String> a = List.of("alpha", "beta", "gamma");
2List<String> b = List.of("alpha", "beta", "gamma");
3List<String> c = List.of("gamma", "beta", "alpha");
4
5System.out.println(a.equals(b)); // true
6System.out.println(a.equals(c)); // false

This is the cleanest option for ordered comparisons and should be your default when order is part of domain meaning.

Same elements ignoring order, but respecting duplicates

If duplicates matter, compare frequency maps.

java
1import java.util.*;
2
3public static boolean sameMultiset(List<String> x, List<String> y) {
4    if (x.size() != y.size()) return false;
5
6    Map<String, Integer> counts = new HashMap<>();
7    for (String s : x) counts.merge(s, 1, Integer::sum);
8    for (String s : y) counts.merge(s, -1, Integer::sum);
9
10    return counts.values().stream().allMatch(v -> v == 0);
11}

This treats lists as multisets and catches differences like [a, a, b] vs [a, b, b].

Same unique values only (duplicates ignored)

If duplicates do not matter, compare sets.

java
Set<String> sx = new HashSet<>(x);
Set<String> sy = new HashSet<>(y);
boolean sameUniqueValues = sx.equals(sy);

Be explicit in code comments because this comparison discards count information.

Null and case handling

Real data may include nulls or inconsistent casing. Normalize before comparison if business rules require it.

java
List<String> normalized = input.stream()
    .map(s -> s == null ? "" : s.trim().toLowerCase(Locale.ROOT))
    .toList();

Apply the same normalization pipeline to both lists before comparing.

Performance considerations

For small lists, readability matters most. For large lists, prefer O(n) frequency-map approaches over repeated contains checks that can degrade toward O(n^2). If comparisons happen frequently, cache normalized representations where safe.

Common Pitfalls

  • Using containsAll both ways and assuming duplicates are compared, which they are not.
  • Forgetting to define whether order matters before writing comparison code.
  • Comparing raw user input without normalization when case or whitespace should be ignored.
  • Converting to sets when duplicate counts are business-critical.
  • Writing custom loops with nested scans and creating avoidable quadratic performance.

Production Readiness Check

Before closing the task, run a short validation loop on representative inputs and one intentional failure case. Confirm that your code path behaves correctly for normal data, empty data, and malformed data. Capture at least one measurable signal such as runtime, memory use, or error rate, then compare it to your baseline so regressions are visible. Keep this check lightweight so it can run in local development and CI without slowing feedback too much. A simple checklist plus one executable smoke test prevents most regressions after refactors and library upgrades.

text
11. Run happy-path example
22. Run edge-case example
33. Run failure-path example
44. Capture one performance or reliability metric
55. Verify output format and error handling

Summary

Comparing two List<String> values correctly starts with semantics: ordered equality, multiset equality, or unique-value equality. Use List.equals for order-sensitive checks, frequency maps when duplicates matter without order, and sets only when duplicates are irrelevant. Normalize input consistently and choose linear-time strategies for larger datasets. Clear comparison rules prevent subtle bugs and make tests communicate intent effectively. Codifying these semantics in helper methods keeps business rules centralized and prevents ad hoc comparison logic from drifting across the codebase.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms