Introduction
Converting a List of objects to a Set is a common task in Java, especially when you need to eliminate duplicates or when you want to perform set operations such as union, intersection, or difference. The Set interface in Java provides a collection that does not allow duplicate elements, making it ideal for these use cases. Java 8 introduced the Stream API, which provides a concise and efficient way to convert a List to a Set. In this guide, we’ll explore how to create a Set from a List of objects using different approaches in Java 8.
Table of Contents
- Problem Statement
- Solution Steps
- Java Program
- Creating a Set from a List of Strings
- Creating a Set from a List of Integers
- Creating a Set from a List of Custom Objects
- Advanced Considerations
- Conclusion
Problem Statement
The task is to create a Java program that:
- Accepts a
Listof objects. - Converts the
Listto aSet. - Outputs the resulting
Set.
Example 1:
- Input: List of strings
["apple", "banana", "orange", "apple"] - Output: Set of strings
["apple", "banana", "orange"]
Example 2:
- Input: List of integers
[1, 2, 3, 4, 1, 2] - Output: Set of integers
[1, 2, 3, 4]
Solution Steps
- Input List: Start with a
Listof objects that can either be hardcoded or provided by the user. - Convert List to Set Using Streams: Use the
StreamAPI andCollectors.toSet()to convert theListto aSet. - Display the Result: Print the resulting
Set.
Java Program
Creating a Set from a List of Strings
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Java 8 - Create Set from List of Strings Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class CreateSetFromList {
public static void main(String[] args) {
// Step 1: Take input list
List<String> fruits = Arrays.asList("apple", "banana", "orange", "apple");
// Step 2: Convert the list to a set using streams
Set<String> fruitSet = fruits.stream()
.collect(Collectors.toSet());
// Step 3: Display the result
System.out.println("Converted Set: " + fruitSet);
}
}
Output
Converted Set: [banana, orange, apple]
Explanation
- The
stream()method is used to create a stream from theListof strings. - The
collect(Collectors.toSet())method collects the stream elements into aSet, automatically eliminating duplicates. - The resulting
Set["banana", "orange", "apple"]is printed to the console.
Creating a Set from a List of Integers
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Java 8 - Create Set from List of Integers Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class CreateSetOfIntegersFromList {
public static void main(String[] args) {
// Step 1: Take input list
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 1, 2);
// Step 2: Convert the list to a set using streams
Set<Integer> numberSet = numbers.stream()
.collect(Collectors.toSet());
// Step 3: Display the result
System.out.println("Converted Set: " + numberSet);
}
}
Output
Converted Set: [1, 2, 3, 4]
Explanation
- The
stream()method is used to create a stream from theListof integers. - The
collect(Collectors.toSet())method collects the stream elements into aSet, automatically eliminating duplicates. - The resulting
Set[1, 2, 3, 4]is printed to the console.
Creating a Set from a List of Custom Objects
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Java 8 - Create Set from List of Custom Objects Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class CreateSetOfCustomObjectsFromList {
public static void main(String[] args) {
// Step 1: Take input list of custom objects
List<Student> students = Arrays.asList(
new Student("Raj", 25),
new Student("Anita", 30),
new Student("Vikram", 22),
new Student("Raj", 25) // Duplicate object
);
// Step 2: Convert the list to a set using streams
Set<Student> studentSet = students.stream()
.collect(Collectors.toSet());
// Step 3: Display the result
studentSet.forEach(student ->
System.out.println(student.getName() + ": " + student.getAge())
);
}
}
// Custom class Student
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
}
Output
Vikram: 22
Raj: 25
Anita: 30
Explanation
- The
stream()method is used to create a stream from theListofStudentobjects. - The
collect(Collectors.toSet())method collects the stream elements into aSet, automatically eliminating duplicates based on theequalsandhashCodemethods defined in theStudentclass. - The resulting
SetofStudentobjects is printed to the console, showing each student’s name and age.
Advanced Considerations
-
Handling Duplicates: When converting a
Listto aSet, any duplicate elements in theListwill be automatically removed. This is because aSetdoes not allow duplicate elements. If you need to maintain duplicates, consider keeping the collection as aList. -
Order Preservation: The
Setinterface does not guarantee any specific order of elements. If you need to maintain the order of elements as they appeared in theList, consider using aLinkedHashSet:Set<String> fruitSet = fruits.stream() .collect(Collectors.toCollection(LinkedHashSet::new)); -
Performance Considerations: Converting a
Listto aSetusing Streams is generally efficient for typical collection sizes. However, for very large collections, test the performance to ensure it meets your application’s needs.
Conclusion
This guide provides methods for creating a Set from a List of objects using Java 8 Streams, covering both simple lists like strings and integers, as well as more complex lists like custom objects. Java 8 Streams offer a concise and readable way to perform this conversion, making your code more maintainable. Depending on your specific use case, you can easily apply the techniques demonstrated in this guide to convert any List into a Set.