Wednesday, January 12, 2022

Java Stream - Convert Stream to Set

In this tutorial you’ll see how to convert a Java Stream to Set using collector method and Collectors.toSet(), Collectors.toUnmodifiableSet() and Collectors.toCollection() methods.

1. In this example a Stream of strings is converted to a Set of strings. For that you can use Collectors.toSet() method which can be passed to the collect method.

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

public class StreamToSet {

  public static void main(String[] args) {
    // Creating stream
    Stream<String> cityStream = Stream.of("Chicago", "Mumbai", 
            "New Delhi", "Paris");
    // Converting Stream to Set
    Set<String> citySet = cityStream.collect(Collectors.toSet());
    // Checking the type of the created Set
    System.out.println(citySet.getClass().getName());
    System.out.println("Set Elements- " + citySet);

  }
}

Output

java.util.HashSet
Set Elements- [New Delhi, Chicago, Mumbai, Paris]

Though the Javadocs say “There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned” but usually HashSet is returned as checked in the example by printing type of the Set.

2. If you want any other type of Set for example LinkedHashSet while converting Stream to Set then you can use Collectors.toCollection(Supplier<C> collectionFactory) method and explicitly specify the type of collection where stream elements are to be stored.

public class StreamToSet {

  public static void main(String[] args) {
    // Creating stream
    Stream<String> cityStream = Stream.of("Chicago", "Mumbai", 
            "New Delhi", "Paris");
    // Converting Stream to Set
    Set<String> citySet = cityStream.collect(Collectors.toCollection(LinkedHashSet :: new));
    // Checking the type of the created Set
    System.out.println(citySet.getClass().getName());
    System.out.println("Set Elements- " + citySet);
  }
}

Output

java.util.LinkedHashSet
Set Elements- [Chicago, Mumbai, New Delhi, Paris]

As evident from the output now the element ordering is maintained because elements are stored in a LinkedHashSet.

3. If you want to ensure that the returned Set is unmodifiable then you can use Collectors.toUnmodifiableSet() method.

public class StreamToSet {

  public static void main(String[] args) {
    Stream<String> cityStream = Stream.of("Chicago", "Mumbai", 
            "New Delhi", "Paris");
    Set<String> citySet = cityStream.collect(Collectors.toUnmodifiableSet());
    System.out.println("Set Elements- " + citySet);
  }
}
Any attempt to modify the returned Set results in error.
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
	at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147)

4. In this example we’ll see how to get a sub-set from a List of objects by using the original List as stream source and using Collectors.toSet() method to collect required elements in a Set.

Employee class

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
  @Override
  public String toString() {
    return "Emp Id: " +  getEmpId() + " Name: " + getName() + " Age: " + getAge();
  }
}

If you want to get a Set of employees having salary greater than 10000 then you can use filter() method along with collector() to collect the filtered elements to the Set.

public class StreamToSet {

  public static void main(String[] args) {
    List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                 new Employee("E002", 35, "Shelly", 'F', 7000), 
                 new Employee("E003", 24, "Mark", 'M', 9000), 
                 new Employee("E004", 37, "Ritu", 'F', 11000),
                 new Employee("E005", 32, "Anuj", 'M', 12000), 
         new Employee("E006", 28, "Amy", 'F', 14000)); 
     
    Set<Employee> tempSet = empList.stream()
                     .filter(e -> e.getSalary() > 10000)
                     .collect(Collectors.toSet());
    System.out.println("Set Elements- " + tempSet);
  }
}

Output

Set Elements- [Emp Id: E005 Name: Anuj Age: 32, Emp Id: E004 Name: Ritu Age: 37, Emp Id: E006 Name: Amy Age: 28]

4. In this example we’ll try to get the name of male employees in a Set. That will mean using map() also along with filter() and collect() methods.

public class StreamToSet {

  public static void main(String[] args) {
    List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                 new Employee("E002", 35, "Shelly", 'F', 7000), 
                 new Employee("E003", 24, "Mark", 'M', 9000), 
                 new Employee("E004", 37, "Ritu", 'F', 11000),
                 new Employee("E005", 32, "Anuj", 'M', 12000), 
         new Employee("E006", 28, "Amy", 'F', 14000)); 
     
    Set<String> tempSet = empList.stream()
                     .filter(e -> e.getGender() == 'M')
                     .map(Employee::getName)
                     .collect(Collectors.toSet());
    System.out.println("Set Elements- " + tempSet);
  }
}

Output

Set Elements- [Mark, Anuj, Ram]

That's all for this topic Java Stream - Convert Stream to Set. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - Convert Stream to List
  2. Java Stream - concat() With Examples
  3. Java Stream API Examples
  4. Java Stream - sorted() With Examples

You may also like-

  1. AutoBoxing And UnBoxing in Java
  2. Heap Memory Allocation in Java
  3. Difference Between equals() Method And equality Operator == in Java
  4. Why no Multiple Inheritance in Java
  5. Creating Tar File And GZipping Multiple Files in Java
  6. Interface in Python
  7. Spring Transaction Attributes - Propagation And Isolation Level Settings
  8. Java Program to Write File in HDFS

No comments:

Post a Comment