Introduction
In Java 8, converting a List
to a Set
is a common task when you want to remove duplicates and maintain unique elements. The Stream API makes this conversion simple and functional. By using the collect()
method along with Collectors.toSet()
, you can easily convert a list into a set.
In this guide, we will learn how to convert a list to a set using Java 8's Stream API.
Solution Steps
- Define the List: Create a list of elements (e.g., strings or integers) that you want to convert to a set.
- Convert the List to a Stream: Use the
stream()
method to convert the list to a stream. - Use
Collectors.toSet()
: Applycollect(Collectors.toSet())
to collect the stream elements into a set, automatically removing duplicates. - Display the Result: Print or use the resulting set.
Java Program
Example 1: Convert a List of Integers to a Set
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class ListToSetExample {
public static void main(String[] args) {
// Step 1: Define the List of integers
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 3, 2);
// Step 2: Convert the List to a Stream and collect to a Set
Set<Integer> numberSet = numbers.stream()
.collect(Collectors.toSet());
// Step 3: Display the Set
System.out.println(numberSet); // Output: [1, 2, 3, 4, 5]
}
}
Output
[1, 2, 3, 4, 5]
Explanation
Step 1: Define the List
We define a list of integers that contains some duplicates:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 3, 2);
Step 2: Convert the List to a Stream and Collect to a Set
We convert the list to a stream using stream()
and collect the elements into a set using Collectors.toSet()
. The set automatically removes duplicate elements:
Set<Integer> numberSet = numbers.stream()
.collect(Collectors.toSet());
Step 3: Display the Result
We print the resulting set, which contains only unique elements:
System.out.println(numberSet);
Example 2: Convert a List of Strings to a Set
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class ListToSetStringExample {
public static void main(String[] args) {
// Step 1: Define the List of strings
List<String> fruits = Arrays.asList("Apple", "Banana", "Apple", "Orange", "Banana");
// Step 2: Convert the List to a Stream and collect to a Set
Set<String> fruitSet = fruits.stream()
.collect(Collectors.toSet());
// Step 3: Display the Set
System.out.println(fruitSet); // Output: [Apple, Banana, Orange]
}
}
Output
[Apple, Banana, Orange]
Explanation
Step 1: Define the List
We define a list of strings that contains some duplicates:
List<String> fruits = Arrays.asList("Apple", "Banana", "Apple", "Orange", "Banana");
Step 2: Convert the List to a Stream and Collect to a Set
We use stream()
to convert the list to a stream and collect(Collectors.toSet())
to collect the elements into a set, automatically removing duplicates:
Set<String> fruitSet = fruits.stream()
.collect(Collectors.toSet());
Step 3: Display the Result
We print the resulting set of unique strings:
System.out.println(fruitSet);
Example 3: Convert a List of Custom Objects to a Set
You can also convert a list of custom objects into a set. To handle this correctly, the custom object class should override equals()
and hashCode()
methods to ensure proper uniqueness.
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class ListToSetCustomObjects {
public static void main(String[] args) {
// Step 1: Define a list of Employee objects
List<Employee> employees = Arrays.asList(
new Employee("Ravi", 30),
new Employee("Amit", 25),
new Employee("Ravi", 30), // Duplicate Employee
new Employee("Pooja", 35)
);
// Step 2: Convert the List to a Stream and collect to a Set
Set<Employee> employeeSet = employees.stream()
.collect(Collectors.toSet());
// Step 3: Display the Set
employeeSet.forEach(System.out::println); // Output: Only unique employees
}
}
class Employee {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return age == employee.age && name.equals(employee.name);
}
@Override
public int hashCode() {
return name.hashCode() + age;
}
@Override
public String toString() {
return name + ": " + age;
}
}
Output
Amit: 25
Ravi: 30
Pooja: 35
Explanation
Step 1: Define the List of Custom Objects
We define a list of Employee
objects, with one duplicate entry (Ravi
, age 30):
List<Employee> employees = Arrays.asList(
new Employee("Ravi", 30),
new Employee("Amit", 25),
new Employee("Ravi", 30),
new Employee("Pooja", 35)
);
Step 2: Convert the List to a Stream and Collect to a Set
We use stream()
and collect(Collectors.toSet())
to convert the list to a set:
Set<Employee> employeeSet = employees.stream()
.collect(Collectors.toSet());
Step 3: Display the Result
We print the unique employees using forEach()
. The equals()
and hashCode()
methods ensure that only unique employees are added to the set:
employeeSet.forEach(System.out::println);
Conclusion
In Java 8, converting a List
to a Set
is simple and efficient using the Stream API. The collect(Collectors.toSet())
method automatically removes duplicate elements, ensuring uniqueness in the resulting set. This approach works for primitive types, strings, and even custom objects, provided that you override equals()
and hashCode()
correctly.
Comments
Post a Comment
Leave Comment