Mengen (Set) in Java 17: Ausführlicher Leitfaden
Sets in Java
What is a Set and why is it needed?
Imagine you have a box where you can only put unique items. If you try to put two identical apples in it, the second one simply won't fit — the box already has that apple. In programming, such a "box" is called a Set.
A Set is a collection that stores elements without duplicates. The order of elements in a regular set doesn't matter. The main rule is: each element can only appear once.
When is this useful?
- You need to collect only unique pizza ingredients
- Store a contact list without duplicates
- Check if a product is on the mandatory list
- Merge two shopping lists, removing duplicates
Basic Syntax
In Java 17, the most commonly used implementation is HashSet — the fastest and simplest set implementation. Here's how to work with it:
// Create an empty set for strings
Set<String> names = new HashSet<>();
// Add elements
names.add("Apple");
names.add("Banana");
names.add("Apple"); // Won't be added — already exists!
// Check the size
System.out.println(names.size()); // Output: 2
// Check if an element exists
if (names.contains("Banana")) {
System.out.println("Banana is in the set");
}
// Remove an element
names.remove("Banana");
// Iterate over all elements
for (String fruit : names) {
System.out.println(fruit);
}
Analysis of Typical Tasks
Task 1: Unique Pizza Ingredients
The user enters ingredients separated by commas. You need to output only the unique ones.
import java.util.*;
public class UniqueIngredients {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter ingredients separated by commas:");
String input = scanner.nextLine();
// Split the string by commas
String[] parts = input.split(",");
// Create a set for unique ingredients
Set<String> ingredients = new HashSet<>();
// Add each ingredient (remove whitespace)
for (String ingredient : parts) {
ingredients.add(ingredient.trim());
}
System.out.println("Unique ingredients: " + ingredients);
System.out.println("Count: " + ingredients.size());
}
}
Example output:
Enter ingredients separated by commas:
cheese, tomato, cheese, basil, tomato, olives
Unique ingredients: [cheese, tomato, basil, olives]
Count: 4
Task 2: Merging Shopping Lists
You have your own list, guests add theirs. You need to get the final list without duplicates.
import java.util.*;
public class ShoppingList {
public static void main(String[] args) {
// Your preliminary list
Set<String> myList = new HashSet<>();
myList.add("Cola");
myList.add("Chips");
myList.add("Cookies");
// Guests added their wishes
Set<String> guestsAdded = new HashSet<>();
guestsAdded.add("Juice");
guestsAdded.add("Chips"); // Duplicate!
guestsAdded.add("Nuts");
// Merge — all unique elements from both sets
myList.addAll(guestsAdded);
System.out.println("Final shopping list:");
for (String item : myList) {
System.out.println("- " + item);
}
}
}
Example output:
Final shopping list:
- Cola
- Chips
- Cookies
- Juice
- Nuts
Task 3: Removing Extras from a List
You have a list of products. You decided to remove some of them. You need to delete them from the set.
import java.util.*;
public class RemovingExtras {
public static void main(String[] args) {
Set<String> purchases = new HashSet<>();
purchases.add("Milk");
purchases.add("Bread");
purchases.add("Eggs");
purchases.add("Cheese");
purchases.add("Butter");
System.out.println("Current list: " + purchases);
System.out.println("What to remove? Enter separated by commas:");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] toRemove = input.split(",");
for (String item : toRemove) {
purchases.remove(item.trim());
}
System.out.println("Remaining: " + purchases);
}
}
Example output:
Current list: [Milk, Bread, Eggs, Cheese, Butter]
What to remove? Enter separated by commas:
Bread, Butter
Remaining: [Milk, Eggs, Cheese]
Task 4: Checking Product Availability
The store has a mandatory list of products. You need to check if all of them are in stock.
import java.util.*;
public class ProductCheck {
public static void main(String[] args) {
Set<String> mandatory = new HashSet<>();
mandatory.add("Bread");
mandatory.add("Milk");
mandatory.add("Eggs");
Scanner scanner = new Scanner(System.in);
System.out.println("Enter products in stock separated by commas:");
String input = scanner.nextLine();
Set<String> stock = new HashSet<>();
for (String product : input.split(",")) {
stock.add(product.trim());
}
// Check if all mandatory products are in stock
if (stock.containsAll(mandatory)) {
System.out.println("All mandatory products are in stock!");
} else {
System.out.println("Some mandatory products are missing!");
}
}
}
Example output:
Enter products in stock separated by commas:
Bread, Milk, Eggs, Cheese
All mandatory products are in stock!