Back to blog
January 8, 20266 min readMarina

Java Collections in Real Systems | Part 1: Set

JavaCollectionsSet

Java Collections in Real Systems | Part 1: Set

Set in Java Collections

When working with Java, choosing the right collection is not an implementation detail. It is a modeling decision.

This is the first post in a short series about Java Collections and how they translate into real-world systems, especially in financial services.

Set is the right choice when uniqueness is a business rule, not just a technical constraint.

Set

  • Collection of unique elements only
  • No access by index
  • Ordering depends on the chosen implementation
  • HashSet

  • No guaranteed order
  • Very fast add, remove, and contains (average O(1))
  • Use case: preventing duplicate transaction processing
  • Set<String> processedTransactions = new HashSet<>();
    processedTransactions.add("TX1001");
    processedTransactions.add("TX1002");
    processedTransactions.add("TX1003");
    processedTransactions.add("TX1002"); // duplicate ignored

    LinkedHashSet

  • Preserves insertion order
  • Slightly slower than HashSet
  • Use case: audit events with traceability
  • Set<String> auditEvents = new LinkedHashSet<>();
    auditEvents.add("LOGIN");
    auditEvents.add("TRANSFER");
    auditEvents.add("LOGOUT");
    auditEvents.add("TRANSFER"); // duplicate ignored, order preserved

    TreeSet

  • Elements stored in sorted order
  • Uses natural ordering or Comparator
  • Use case: sorted limits or thresholds
  • Set<BigDecimal> limits = new TreeSet<>();
    limits.add(new BigDecimal("1000"));
    limits.add(new BigDecimal("500"));
    limits.add(new BigDecimal("2000"));
    limits.add(new BigDecimal("1000")); // duplicate ignored

    Think

  • HashSet → fastest uniqueness guarantee
  • LinkedHashSet → uniqueness + order
  • TreeSet → uniqueness + sorting
  • If you want the big-picture comparison between List, Set, and Map, read the intro:

    List, Set, and Map: Key Differences in Java Collections.

    Next in the series:

    Java Collections in Real Systems | Part 2: List.