January 8, 2024

Java Stream – Convert a Stream to Set

In this tutorial you’ll see how to convert a Stream to Set using collector method and utility methods like toSet() and toCollection() of Collectors class in Java Stream API.

1. A simple example to collect Stream elements into a HashSet.

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

public class StreamToSet {

  public static void main(String[] args) {
    Stream<String> streamElem = Stream.of("A", "B", "C", "D");
    Set<String> setFromStream = streamElem.collect(Collectors.toSet());
    // get type of object
    System.out.println(setFromStream.getClass().getName());
    System.out.println("Elements in the Set- " + setFromStream);
  }
}
Output
java.util.HashSet
Elements in the Set- [A, B, C, D]

As you can see type of the Set returned is java.util.HashSet.

2. If you want to convert the Stream into another implementation of Set say TreeSet then you can use Collectors.toCollection() method.

public class StreamToSet {

  public static void main(String[] args) {
    Stream<String> streamElem = Stream.of("A", "B", "C", "D");
    Set<String> setFromStream = streamElem.collect(
            Collectors.toCollection(TreeSet::new));
    // get type of object
    System.out.println(setFromStream.getClass().getName());
    System.out.println("Elements in the Set- " + setFromStream);
  }
}
Output
java.util.TreeSet
Elements in the Set- [A, B, C, D]

As you can see now the type of the Set is java.util.TreeSet.

3. Converting Stream to Set while filtering some of the elements by providing a condition. For example if you want to store only those elements in the Set which are greater than 10 then you can filter other elements.

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

public class StreamToSet {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(6, 10, 5, 6, 7, 8, 12, 22);
    Set<Integer> setFromStream = numList.stream()
                                        .filter(e -> e > 8)
                                        .collect(Collectors.toSet());
    System.out.println("Elements in the Set- " + setFromStream);
  }
}
Output
Elements in the Set- [22, 10, 12]

In this example we start with a List of integers and use filter() method to filter elements and the returned Stream is converted to a Set.

4. An example with custom object to store the name of only those Students in the Set who have scored more than 75. Let’s say requirement is to store the student names in sorted order for that we can use TreeSet.

Student class used is as follows-

public class Student {
  private int rollNo;
  private String name;
  private String stream;
  private int marks;
  Student(int rollNo, String name, String stream, int marks){
    this.rollNo = rollNo;
    this.name = name;
    this.stream = stream;
    this.marks = marks;
  }
  public int getRollNo() {
    return rollNo;
  }
  public String getName() {
    return name;
  }

  public String getStream() {
    return stream;
  }

  public int getMarks() {
    return marks;
  }

  @Override
  public String toString() {
    return "Roll Number: " +  getRollNo() 
        + " Name: " + getName() + " Marks: " + getMarks();
  }
}
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

public class StreamToSet {

  public static void main(String[] args) {
    List<Student> studentList = Arrays.asList(new Student(1, "Mercy", "Science", 73),
              new Student(2, "Ram", "Science", 99),
              new Student(3, "Priscilla", "Art", 68),
              new Student(4, "Jacques", "Maths", 97),
              new Student(5, "Peter", "Science", 76));
    Set<String> nameSet = studentList.stream()
                     .filter(s -> s.getMarks() > 75)
                     .map(s -> s.getName())
                     .collect(Collectors.toCollection(TreeSet::new));
    System.out.println("Elements in the Set- " + nameSet);
  }
}
Output
Elements in the Set- [Jacques, Peter, Ram]

That's all for the topic Java Stream – Convert a Stream to Set. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment