Java 8 – Create Set from Array

Introduction

Creating a Set from an array is a common task in Java, especially when you need to eliminate duplicates or perform set operations on a collection of elements. The Set interface in Java provides a collection that does not allow duplicate elements, making it an ideal choice when uniqueness is required. Java 8 introduced the Stream API, which offers a concise and efficient way to convert an array into a Set. In this guide, we’ll explore how to create a Set from an array using different approaches in Java 8.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Creating a Set from an Array of Strings
    • Creating a Set from an Array of Integers
    • Creating a Set from an Array of Custom Objects
  • Advanced Considerations
  • Conclusion

Problem Statement

The task is to create a Java program that:

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

Example 1:

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

Example 2:

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

Solution Steps

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

Java Program

Creating a Set from an Array of Strings

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Java 8 - Create Set from Array of Strings Using Streams
 * Author: https://www.rameshfadatare.com/
 */
public class CreateSetFromArray {

    public static void main(String[] args) {
        // Step 1: Take input array
        String[] fruits = {"apple", "banana", "orange", "apple"};

        // Step 2: Convert the array to a set using streams
        Set<String> fruitSet = Arrays.stream(fruits)
                                     .collect(Collectors.toSet());

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

Output

Converted Set: [banana, orange, apple]

Explanation

  • The Arrays.stream(fruits) method creates a stream from the array of strings.
  • The collect(Collectors.toSet()) method collects the stream elements into a Set, automatically eliminating duplicates.
  • The resulting Set ["banana", "orange", "apple"] is printed to the console.

Creating a Set from an Array of Integers

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Java 8 - Create Set from Array of Integers Using Streams
 * Author: https://www.rameshfadatare.com/
 */
public class CreateSetOfIntegersFromArray {

    public static void main(String[] args) {
        // Step 1: Take input array
        Integer[] numbers = {1, 2, 3, 4, 1, 2};

        // Step 2: Convert the array to a set using streams
        Set<Integer> numberSet = Arrays.stream(numbers)
                                       .collect(Collectors.toSet());

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

Output

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

Explanation

  • The Arrays.stream(numbers) method creates a stream from the array of integers.
  • The collect(Collectors.toSet()) method collects the stream elements into a Set, automatically eliminating duplicates.
  • The resulting Set [1, 2, 3, 4] is printed to the console.

Creating a Set from an Array of Custom Objects

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Java 8 - Create Set from Array of Custom Objects Using Streams
 * Author: https://www.rameshfadatare.com/
 */
public class CreateSetOfCustomObjectsFromArray {

    public static void main(String[] args) {
        // Step 1: Take input array of custom objects
        Student[] students = {
                new Student("Raj", 25),
                new Student("Anita", 30),
                new Student("Vikram", 22),
                new Student("Raj", 25) // Duplicate object
        };

        // Step 2: Convert the array to a set using streams
        Set<Student> studentSet = Arrays.stream(students)
                                        .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 Arrays.stream(students) method creates a stream from the array of Student objects.
  • The collect(Collectors.toSet()) method collects the stream elements into a Set, automatically eliminating duplicates based on the equals and hashCode methods defined in the Student class.
  • The resulting Set of Student objects is printed to the console, showing each student’s name and age.

Advanced Considerations

  • Handling Duplicates: When converting an array to a Set, any duplicate elements in the array will be automatically removed. This is because a Set does not allow duplicate elements. If you need to maintain duplicates, consider converting the array to a List instead.

  • Order Preservation: The Set interface does not guarantee any specific order of elements. If you need to maintain the order of elements as they appeared in the array, consider using a LinkedHashSet:

    Set<String> fruitSet = Arrays.stream(fruits)
                                 .collect(Collectors.toCollection(LinkedHashSet::new));
    
  • Performance Considerations: Converting an array to a Set using Streams is generally efficient for typical collection sizes. However, for very large arrays, test the performance to ensure it meets your application’s needs.

Conclusion

This guide provides methods for creating a Set from an array using Java 8 Streams, covering both simple arrays like strings and integers, as well as more complex arrays 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 array into a Set.

Leave a Comment

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

Scroll to Top