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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Use a HashSet to remember categories already encountered, then check the boolean returned by add as you scan the input. A return value of true means this is the first occurrence; false means an equal value has appeared before. If “unique” means a category appearing exactly once overall, count frequencies instead.

Find first occurrences and repeats in one pass

This example keeps the original list intact and records first-seen and repeated occurrences in separate lists:

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 first-occurrence list is [Books, Games, Music] and the repeated-occurrence list is [Books, Games]. The output lists retain scan order; the HashSet is only used for membership checks. List.of requires Java 9 or later; for earlier Java versions, use Arrays.asList and import java.util.Arrays.

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

What the condition means

A Set cannot contain duplicate elements. On each iteration, seen.add(category) both attempts to add the category and tells you whether the set changed. If it returns true, the category was not already in the set. If it returns false, an equal category was already present. Oracle’s Collections tutorial describes the Set contract.

Choose the meaning of “unique” you need

One representative of each distinct value

The example places each category in firstOccurrences the first time it appears. A later matching value goes to repeatedOccurrences. If you only need one copy of every distinct value, you can collect the set itself, but a plain HashSet does not preserve display order.

Values that appear exactly once

The scan above labels later appearances as repeats; it does not remove an earlier first occurrence from the first-occurrence list. To return only categories whose total frequency is one, count every category first, then select entries with a count of one. A frequency map is a better fit when you need totals or exact-once results.

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.add(category);
    }
}

This produces one entry per input occurrence whose value occurs exactly once. Because such a value has only one occurrence, the resulting list has no repeated entries.

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

Equality determines whether categories match

The set checks whether values are equal according to their equals and hashCode behavior. Strings with the same text count as the same category. For a custom category class, decide which fields define category identity and implement both methods consistently using those fields. A hash collision by itself does not make two values equal; equality is also checked.

Do not change fields used by equals or hashCode while an object is stored in a set. A changed hash behavior can prevent the set from locating that object as expected. A HashSet allows null; repeated null values are still treated as one set member.

Choose a set implementation based on output needs

Implementation Order Use it when Trade-off
HashSet No iteration-order guarantee You need membership checks or deduplication and order does not matter Basic operations are expected to be constant time when hashes disperse elements properly; see the Java SE 26 API.
LinkedHashSet Insertion order You want one copy of each value in first-insertion order Maintaining order has a modest cost compared with HashSet; see Oracle’s Set implementations tutorial.
TreeSet Sorted order You need values ordered according to their natural ordering or a comparator Sorting changes the output order from input order; the tutorial describes it as substantially slower than HashSet.
Frequency map Depends on map and result collection You need counts or values appearing exactly once Requires storing counts rather than only membership.

If first-seen and repeated outputs must both follow input order, separate lists—as in the example—make that requirement explicit. Do not rely on iterating a HashSet for stable or input-ordered output: the Java SE 26 API makes no iteration-order guarantee.

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

Complexity and version context

The scan performs one set insertion attempt per input element, plus list additions for the results. The Java API describes basic HashSet operations as expected constant time when the hash function disperses elements properly; it is not an unconditional guarantee for every input. The API link above is for Java SE 26. Oracle’s Collections tutorial notes that its examples were written for JDK 8, so consult the relevant API documentation for details specific to a newer Java release.

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

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.