Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Collections

Java Sets: HashSet, LinkedHashSet and TreeSet

A guest list refuses the second Asha and add returns false. The same five arrivals print in three orders: HashSet scatters, LinkedHashSet remembers arrival, TreeSet sorts. Then a signup list with Neha twice becomes a set with her once, order kept.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Collections

What you will learn

  • Use a Set to keep each value once and read add's true or false
  • Explain how hashCode and equals let a set spot a repeat
  • Predict the order of a HashSet, a LinkedHashSet and a TreeSet
  • Remove repeats from a list while keeping its order

Before you start

  • Java equals and hashCode
  • From arrays to collections: the framework map

Sometimes you need only unique values. You could use a list and write your own logic to remove duplicates, but that's tedious. A set simply doesn't allow them.

A guest list, each name once

package org.studyeasy.s04l08;

import java.util.HashSet;
import java.util.Set;

public class Ex01_GuestList {
    public static void main(String[] args) {
        Set<String> guests = new HashSet<>();
        guests.add("Asha");
        guests.add("Ravi");

        boolean addedAgain = guests.add("Asha");  // already on the list
        System.out.println("Added again: " + addedAgain);
        System.out.println("Size:        " + guests.size());
        System.out.println("Has Ravi:    " + guests.contains("Ravi"));
    }
}
Added again: false
Size:        2
Has Ravi:    true

add returns a boolean. Asha is already there, so the second add gives false and nothing changes. Size stays 2, and contains confirms Ravi is in.

How does the set know? It uses the hashCode and equals pair: first the hash code, then equals. A name that isn't there is stored and add returns true; a name that is there is left alone and add returns false. String and wrappers like Integer already have both methods written, so there's nothing to implement.

Same names, three orders

package org.studyeasy.s04l08;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public class Ex02_ThreeSets {
    public static void main(String[] args) {
        Set<String> hash = new HashSet<>();
        Set<String> linked = new LinkedHashSet<>();
        Set<String> tree = new TreeSet<>();

        String[] arrivals = {"Neha", "Asha", "Ravi", "Neha", "Priya"};
        for (String name : arrivals)  {   // same names, same order
            hash.add(name);
            linked.add(name);
            tree.add(name);
        }
        System.out.println("HashSet:       " + hash);
        System.out.println("LinkedHashSet: " + linked);
        System.out.println("TreeSet:       " + tree);
    }
}
HashSet:       [Priya, Neha, Asha, Ravi]
LinkedHashSet: [Neha, Asha, Ravi, Priya]
TreeSet:       [Asha, Neha, Priya, Ravi]

Neha arrives twice, so every set keeps her once and all three hold four names. Only the order differs.

Five arrivals: Neha, Asha, Ravi, Neha, Priya. All three sets refuse the second Neha. HashSet places names by hash code into buckets and prints Priya, Neha, Asha, Ravi with no promised order. LinkedHashSet uses buckets plus a thread through arrival order: Neha, Asha, Ravi, Priya. TreeSet builds a sorted tree with Neha at the root, Asha left, Ravi right and Priya left of Ravi; read left to right it gives Asha, Neha, Priya, Ravi. Arrivals: Neha, Asha, Ravi, Neha (refused), Priya HashSet buckets by hash code Priya, Neha,Asha, Ravi no promised order LinkedHashSet buckets plus a thread Neha, Asha,Ravi, Priya arrival order TreeSet Neha AshaRavi Priya
HashSet scatters, LinkedHashSet remembers, TreeSet sorts.
  • The HashSet puts each name in a bucket picked by its hash code and prints bucket by bucket. That order is Java's choice and comes with no promise; don't rely on it.
  • The LinkedHashSet uses the same buckets but also keeps a thread through the names in the order they arrived, and prints by following it.
  • The TreeSet builds a sorted tree. Neha is the root, Asha goes left, Ravi right, and Priya sits between Neha and Ravi. Read left to right, it's alphabetical.

One trap: tree.add(null) throws a NullPointerException. A TreeSet compares every value, and it can't compare null with a name.

Drop the repeat, keep the order

List<String> signups = new ArrayList<>();
signups.add("Neha");
signups.add("Asha");
signups.add("Neha");              // signed up twice
signups.add("Priya");

// the repeat drops out, the order stays
Set<String> unique = new LinkedHashSet<>(signups);

System.out.println("List: " + signups);
System.out.println("Set:  " + unique);
List: [Neha, Asha, Neha, Priya]
Set:  [Neha, Asha, Priya]

A list happily keeps both Nehas. Passing it into a new LinkedHashSet drops the second one, and the order stays, so four entries become three. A set has no index, though: unique.get(0) is "cannot find symbol".

Which set for which job

HashSetLinkedHashSetTreeSet
Repeatsrefusedrefusedrefused
Orderno promisearrival ordersorted
Speedfastestclose behinda little slower (keeps sorting)
Pick it whenorder doesn't matterorder must stayoutput must be sorted

Default to HashSet. To sort by something other than alphabetical order, you need a comparator: see Comparable and Comparator.

Keep going in Java · 50 of 79

Previous
Java LinkedList vs ArrayList: Nodes or an Array
Next post
Java Sorting with Comparable and Comparator
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java equals and hashCode: Why a HashSet Needs Both

== asks if it's the very same object, equals compares values, and hashCode puts equal objects in the same HashSet bucket. Three small programs show what breaks when hashCode is missing.

From Arrays to Collections: The Java Collections Framework Map

An array of 3 students can't seat John, so Java throws Index 3 out of bounds. A List just grows. Then the map of the framework: List, Set and Queue under Collection, Map beside it, four behaviours in one program, and why the variable type should be the interface.

Java Wrapper Classes and Autoboxing

List<int> won't compile because a list holds objects only. Integer.valueOf puts 87 in a box and intValue takes it out, and add and get do it for you. Then two traps: 128 == 128 is false, and unboxing a null Integer throws a NullPointerException.

Java ArrayList: The Stretchy Array

add, add at an index, get, set, remove and contains on a list of courses and a cart, why Git at index 1 pushes SQL and Spring right, removing scores below 50 with an Iterator or removeIf, List.of that can't change, and the array inside that grows from 10 to 15.

On this page

  • A guest list, each name once
  • Same names, three orders
  • Drop the repeat, keep the order
  • Which set for which job
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.