Java 8 – Convert Set to List

Introduction

Converting a Set to a List is a common task in Java, particularly when you need to maintain the order of elements, perform list-specific operations, or simply require a mutable collection. While the Set interface does not allow duplicate elements and does not guarantee order, a List can store duplicates and maintain the order of insertion. Java 8 introduced the Stream API, which provides a concise and efficient way to perform this conversion. In this guide, we’ll explore how to convert a Set to a List using different approaches in Java 8.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Converting a Set of Strings to a List
    • Converting a Set of Integers to a List
    • Converting a Set of Custom Objects to a List
  • Advanced Considerations
  • Conclusion

Problem Statement

The task is to create a Java program that:

  • Accepts a Set of elements.
  • Converts the Set to a List.
  • Outputs the resulting List.

Example 1:

  • Input: Set of strings ["apple", "banana", "orange"]
  • Output: List ["apple", "banana", "orange"]

Example 2:

  • Input: Set of integers [1, 2, 3, 4]
  • Output: List [1, 2, 3, 4]

Solution Steps

  1. Input Set: Start with a Set of elements that can either be hardcoded or provided by the user.
  2. Convert Set to List Using Streams: Use the Stream API and the collect() method to convert the Set to a List.
  3. Display the Result: Print the resulting List.

Java Program

Converting a Set of Strings to a List

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Java 8 - Convert Set of Strings to List Using Streams
 * Author: https://www.rameshfadatare.com/
 */
public class ConvertSetToList {

    public static void main(String[] args) {
        // Step 1: Take input set
        Set<String> fruits = new HashSet<>();
        fruits.add("apple");
        fruits.add("banana");
        fruits.add("orange");

        // Step 2: Convert the set to a list using streams
        List<String> fruitList = fruits.stream()
                                       .collect(Collectors.toList());

        // Step 3: Display the result
        System.out.println("Converted List: " + fruitList);
    }
}

Output

Converted List: [banana, orange, apple]

Explanation

  • The stream() method is used to create a stream from the Set of strings.
  • The collect(Collectors.toList()) method collects the stream elements into a List.
  • The resulting List ["banana", "orange", "apple"] is printed to the console.

Converting a Set of Integers to a List

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Java 8 - Convert Set of Integers to List Using Streams
 * Author: https://www.rameshfadatare.com/
 */
public class ConvertSetOfIntegersToList {

    public static void main(String[] args) {
        // Step 1: Take input set
        Set<Integer> numbers = new HashSet<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);

        // Step 2: Convert the set to a list using streams
        List<Integer> numberList = numbers.stream()
                                          .collect(Collectors.toList());

        // Step 3: Display the result
        System.out.println("Converted List: " + numberList);
    }
}

Output

Converted List: [1, 2, 3, 4]

Explanation

  • The stream() method is used to create a stream from the Set of integers.
  • The collect(Collectors.toList()) method collects the stream elements into a List.
  • The resulting List [1, 2, 3, 4] is printed to the console.

Converting a Set of Custom Objects to a List

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Java 8 - Convert Set of Custom Objects to List Using Streams
 * Author: https://www.rameshfadatare.com/
 */
public class ConvertCustomObjectsSetToList {

    public static void main(String[] args) {
        // Step 1: Take input set of custom objects
        Set<Student> students = new HashSet<>();
        students.add(new Student("Raj", 25));
        students.add(new Student("Anita", 30));
        students.add(new Student("Vikram", 22));

        // Step 2: Convert the set to a list using streams
        List<Student> studentList = students.stream()
                                            .collect(Collectors.toList());

        // Step 3: Display the result
        studentList.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;
    }
}

Output

Vikram: 22
Raj: 25
Anita: 30

Explanation

  • The stream() method is used to create a stream from the Set of Student objects.
  • The collect(Collectors.toList()) method collects the stream elements into a List.
  • The resulting List of Student objects is printed to the console, showing each student’s name and age.

Advanced Considerations

  • Order Preservation: While converting a Set to a List, the order of elements in the resulting list will depend on the type of Set you started with. For example, if you use a LinkedHashSet, the order will be preserved. If you use a HashSet, the order might appear random.

    If order is important, consider using a LinkedHashSet to maintain the insertion order:

    Set<String> orderedSet = new LinkedHashSet<>(fruits);
    List<String> orderedList = orderedSet.stream()
                                         .collect(Collectors.toList());
    
  • Handling Duplicates: If you need to ensure that duplicates are not reintroduced when converting from a Set to a List, remember that Set inherently does not allow duplicates, so any conversion back to a List will retain this property unless you explicitly modify the list.

  • Performance Considerations: Converting a Set to a List using 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 converting a Set to a List using Java 8 Streams, covering both simple sets like strings and integers, as well as more complex sets 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 Set into a List.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top