October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Java HashSet: How to Separate First-Seen and Repeated Categories

A Java HashSet scan distinguishes first occurrences from repeats; use a frequency map when “unique” means appearing exactly once.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To find repeated categories in Java without changing the input list, scan it once and use the boolean result of HashSet.add(): true means the value is new to the set; false means an equal value has already appeared. Store each result in separate lists if you want both first occurrences and repeated occurrences in input order.

Separate first occurrences from repeats in one pass

A Set cannot contain duplicate elements, as Oracle’s Java Collections tutorial explains. When scanning a list, HashSet.add(value) tells you whether adding that value changed the set: it returns true for a first occurrence and false when the set already contains an equal value. The input list remains unchanged.

As an Amazon Associate I earn from qualifying purchases.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CategoryDuplicates {
    public static void main(String[] args) {
        List<String> categories = List.of("Books", "Games", "Books", "Music", "Games");
        Set<String> seen = new HashSet<>();
        List<String> firstOccurrences = new ArrayList<>();
        List<String> repeatedOccurrences = new ArrayList<>();

        for (String category : categories) {
            if (seen.add(category)) {
                firstOccurrences.add(category);
            } else {
                repeatedOccurrences.add(category);
            }
        }

        System.out.println("First occurrences: " + firstOccurrences);
        System.out.println("Repeated occurrences: " + repeatedOccurrences);
    }
}

For this input, the lists contain [Books, Games, Music] and [Books, Games], respectively. The lists preserve scan order; the set is only used for membership checks. List.of is available in Java 9 and later. On an older JDK, use Arrays.asList("Books", "Games", "Books", "Music", "Games") and import java.util.Arrays.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Decide what “unique” means for your output

“Unique” can mean either one representative of each distinct category or categories whose total frequency is exactly one. The example’s firstOccurrences list gives one representative of each category, even if that category appears again later. Its repeatedOccurrences list includes every occurrence after the first. Neither list, by itself, answers which categories appeared exactly once overall.

Keep categories that appear exactly once

For an exact frequency check, count values first, then select those with a count of one. A map makes that meaning explicit:

import java.util.HashMap;
import java.util.Map;

Map<String, Integer> counts = new HashMap<>();
for (String category : categories) {
    counts.merge(category, 1, Integer::sum);
}

List<String> appearingOnce = new ArrayList<>();
for (String category : categories) {
    if (counts.get(category) == 1 && !appearingOnce.contains(category)) {
        appearingOnce.add(category);
    }
}

Iterating the original list in the second pass preserves its order in appearingOnce. The contains check prevents a category with count one from being added more than once; alternatively, collect qualifying keys from the map if their order does not matter.

Choose a collection based on ordering and counting needs

Collection When it fits Ordering and trade-off
HashSet Membership checks and duplicate detection when display order is irrelevant. No iteration-order guarantee. Basic operations are expected to take constant time when hash values disperse elements properly, according to the Java SE 26 API.
LinkedHashSet Keep one copy of each category in first-insertion order. Retains insertion order, with a modest cost compared with HashSet, according to the Oracle collections implementations tutorial.
TreeSet Keep distinct categories in sorted order. Orders values rather than preserving input order; it is substantially slower than HashSet, according to the same Oracle tutorial.
Frequency map Find counts or categories whose frequency is exactly one. Stores a count per distinct value; choose an ordered map or separately preserve input order if the output needs a particular order.

If you need first-seen and repeated values in separate outputs, the lists in the example are the simplest way to preserve both sequences. Iterating a HashSet to produce output does not preserve the original list order: Oracle’s Java SE 26 API explicitly makes no iteration-order guarantee.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make equality match the meaning of “same category”

A set decides whether values are duplicates using equality and hash codes, not by comparing every field automatically. Strings already have value-based equality, so equal text is treated as the same category. For a custom category class, implement equals and hashCode using the same fields that define category identity—for example, a stable category ID if names can vary.

  • Two objects that represent the same category should compare equal and return the same hash code.
  • A hash collision alone does not make two values equal; equality is also considered.
  • Do not change fields used by equals or hashCode while an object is in a set. Doing so can make membership checks behave unexpectedly.

A HashSet permits one null element; any later null is considered already present. Decide whether null is valid input and handle it consistently with your category rules.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What the usual performance claim does—and does not—mean

Oracle describes HashSet as the best-performing general-purpose Set implementation and documents expected constant-time basic operations when the hash function disperses elements properly in its Java SE 26 API. This is a conditional expectation, not a guarantee that every input or custom hashCode implementation will perform equally well. The one-pass duplicate scan does one set insertion attempt per input element; the frequency-map approach also processes the input once to build counts, then makes a further pass to select the desired results.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.