Java Tutorial

Java Set

A Set holds unique elements — add the same value twice and it still appears once. Use it when duplicates are noise.

HashSet basics

HashSet is the common Set. add returns false if the element was already present. There is no index — membership is by equals / hashCode.

Example

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

public class Main {
  public static void main(String[] args) {
    Set tags = new HashSet<>();
    tags.add("java");
    tags.add("java");
    tags.add("tips");
    System.out.println(tags.size());      // 2
    System.out.println(tags.contains("java"));
  }
}

Deduplicate a list

Passing a list into a set constructor (or adding each element) drops duplicates. Convert back to a list if you need order and indexing again.

Example

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

public class Main {
  public static void main(String[] args) {
    List raw = List.of(1, 2, 2, 3, 1);
    Set unique = new HashSet<>(raw);
    System.out.println(unique);   // [1, 2, 3] (order not guaranteed)
  }
}

LinkedHashSet keeps insertion order

When you care about uniqueness and first-seen order, use LinkedHashSet.TreeSet sorts elements instead.

Example

import java.util.LinkedHashSet;
import java.util.Set;

public class Main {
  public static void main(String[] args) {
    Set seen = new LinkedHashSet<>();
    seen.add("first");
    seen.add("second");
    seen.add("first");
    System.out.println(seen);   // [first, second]
  }
}

Sets are perfect for “have I seen this id?” checks — contains on a HashSet is typically near constant time.

Set algebra

addAll is union, retainAll is intersection, removeAll is difference. Work on a copy if you need to keep the original.

Example

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

public class Main {
  public static void main(String[] args) {
    Set a = new HashSet<>();
    a.add(1); a.add(2); a.add(3);
    Set b = new HashSet<>();
    b.add(2); b.add(3); b.add(4);
    Set both = new HashSet<>(a);
    both.retainAll(b);
    System.out.println(both);   // [2, 3]
  }
}

HashSet iteration order is not defined. Do not write tests that assume a particular print order unless you use LinkedHashSet or TreeSet.

Try It Yourself

Exercise: Add the words "red", "blue", "red" to a HashSet and print size(). What do you get?

Show solution
import java.util.HashSet;
import java.util.Set;

Set colors = new HashSet<>();
colors.add("red");
colors.add("blue");
colors.add("red");
System.out.println(colors.size());   // 2

The second "red" is ignored because the set already contains an equal element.

Key Takeaways

  • Sets store unique elements; duplicates are ignored.
  • HashSet is unordered; LinkedHashSet keeps insertion order; TreeSet sorts.
  • Great for deduplication and fast contains checks.
  • retainAll / addAll / removeAll implement set algebra.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.

Biology

Unique species ids

A set drops duplicates. Three sightings of the same id still count as one species in the set.

Example

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Set<String> ids = new HashSet<>(List.of("fox", "owl", "fox"));
    System.out.println(ids.size());
  }
}

Maths

Intersection size

retainAll keeps only shared members. The size of the result is how many elements sit in both sets.

|A ∩ B|

Example

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Set<Integer> a = new HashSet<>(List.of(1, 2, 3));
    Set<Integer> b = new HashSet<>(List.of(2, 3, 4));
    a.retainAll(b);
    System.out.println(a.size());
  }
}

FAQ: Java Set

Common questions about this page.

What is the StudyGrid Java tutorial?

The StudyGrid Java tutorial is a full beginner-to-advanced track: syntax, types, input, loops, methods, classes, collections, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run java hashset examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn java hashset in this Java Java lesson (Java Set).

Is the Java editor the same as Try Python or Try C++?

No. Try Java compiles with javac at /java/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. Java lessons never open those editors.

Do I need to install a JDK to learn Java?

No. Open a chapter, click Try it in Java, and compile in the browser. You can also download a .java file and compile locally with javac.

Where should I start the Java tutorial?

Start at Java Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open Java Examples, then generics, map, and lambdas. Use Next at the bottom of each chapter.

Is the Java tutorial free?

Yes. The Java workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.