Hackforge Academy

Category: React • Beginner

Published on 14 Feb 2026

Explanation

In Java, Set is an interface in the Collection Framework that represents a collection of unique elements. It does NOT allow duplicates May or may not maintain insertion order (depends on implementation) Package: import java.util.Set;

Code Example


Explanation

In Java, Set is an interface in the Collection Framework that represents a collection of unique elements. It does NOT allow duplicates May or may not maintain insertion order (depends on implementation) #white-Package: import java.util.Set;

Code Example


Explanation

Declaration of Set

Code Example

import java.util.*;

Set<String> set = new HashSet<>();

Best practice: Use interface reference (Set)
Object of implementing class (HashSet)

Explanation

HashSet Example

Code Example

import java.util.*;

public class SetExample {
    public static void main(String[] args) {

        Set<String> languages = new HashSet<>();

  languages.add("Java");
  languages.add("Python");
  languages.add("Java");  
 // Duplicate ignored
System.out.println(languages);
    }
}

Explanation

Checking Duplicate Behavior

Code Example

Set<Integer> numbers = new HashSet<>();

numbers.add(10));
numbers.add(10));
//will not add one more time

Explanation

Looping Through Set

Code Example

Enhanced For Loop
for (String lang : languages) {
    System.out.println(lang);
}

forEach (Java 8)
languages.forEach(System.out::println);

Explanation

#white-LinkedHashSet Maintains Order

Code Example

Set<String> set = new LinkedHashSet<>();

set.add("A");
set.add("B");
set.add("C");

System.out.println(set);

Explanation

TreeSet Example Sorted Order

Code Example

Set<Integer> set = new TreeSet<>();

set.add(30);
set.add(10);
set.add(20);

System.out.println(set);

Explanation

When to Use Set? When duplicates are NOT allowed When you need fast lookup When uniqueness matters #white-Example: Storing unique usernames Removing duplicates from list

Code Example


Want structured learning with real projects?

Join our Weekend Live Workshop and become job-ready faster.