Collectors toSet() method in Java 8


Collections reverse order class is a reverse order method, which is encoded in the collections class. It is present in the java.util package. It returns a comparator as a result, which is a predefined comparator in nature. By using this comparator package, we can rearrange the collections of a particular data set in a reverse manner. The Collectors toSet() is a collector class, which itself returns a collector and accumulates those particular elements as an input into a new set. toSet() is an unordered collector class which is not accountable to preserve the order of the encounter of some input elements. To use this function, we need to remember that there will be no assurance on the type, mutability and serializability of those particular data. And there is no thread-safety of the Set return. Here is an example −

int[] array = { 1, 2, 3, 4, 5 };
Set<Integer> set = Stream.of(array)
.flatMapToInt(Arrays::stream).boxed().collect(Collectors.toSet());

Algorithm to Perform the Function of Collections ToSet in Java

In this possible algorithm, we are going to explain how to declare and construct a toSet function by which we can bind the all data in a particular data set.

  • Step 1 − Start the process

  • Step 2 − Import and declare the usable packages to run the process.

  • Step 3 − Declare a public class.

  • Step 4 − Mention the argument string.

  • Step 5 − Create a stream value node.

  • Step 6 − Populate this stream with some data.

  • Step 7 − Declare a collection function with the toSet().

  • Step 8 − Override the data set.

  • Step 9 − Select stream 1 and stream 2.

  • Step 10 − Flat operation on the data set.

  • Step 11 − Return the value.

  • Step 12 − Terminate the process.

Syntax to Perform the Function of Collections ToSet in Java

Set<Integer> set = Stream.of(1, 2, 3, 4, 5).collect(Collectors.toSet());{
   Person p1 = new Person("P1");
   p1.add(1);
   p1.add(5);
   p1.add(10);
   Person p2 = new Person("P2");
   Collectors toSet() in Java with Examples
   p2.add(10);
   p2.add(20);
   p2.add(50);
   p2.add(5);
   List team = new ArrayList<>();
   team.add(p1);
   team.add(p2);
   Set setOfDistinctNote = team.stream()
   .map( p -> p.getNotes())
   .flatMap(l -> l.stream())
   .collect(Collectors.toSet());
   System.out.println("Number of distinct notes in team : " +
   setOfDistinctNote);
}
class Person{
	private String name;
	private List notes = new ArrayList<>();
	public Person(String name){
		this.name = name;
	}
	public void add(Integer note){ notes.add(note);
	}
	public List getNotes(){ 
		return notes;
	}
	@Override public String toString(){
		return String.format(name + notes);
	}
}

In this possible syntax above, we have tried to build a general logic code by using some Java logics. With this syntax you can experience the working process of the collectors toSet() function. Now we are heading towards the possible approaches by which we will learn to solve the problem statement in an efficient way.

Approaches to Follow

  • Approach 1 − Java code to show the implementation of Collectors toSet() function by using the stream class method

  • Approach 2 − Java program to demonstrate how we can use the Collectors class to convert a set or stream of values into a Set

Approach 1: Demonstrate the Working of Collections.sort()

In these possible approaches, we are going to apply the T, A, R theory present in the collector class. Here −

  • T − is the input elements types we are going to use in this process.

  • Interface collector class − It is a mutable operation class which helps to put the elements into the container class.

    • T − an input element type with the reduction.

    • A − mutable accumulation with a reduction.

    • R − a result type with a reduction.

  • Set − collection of some data elements with no duplicacy. It dose not contain any pairs as well as null elements.

Example 1

//Java code to show the implementation of Collectors toSet() function by using the stream class method
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ARBRDD {
   public static void main(String[] args){
      Stream<String> s = Stream.of("BANGLADESH",
      "INDIA",
      "TRAIN",
      "MAITREE EXPRESS");
      Set<String> mySet = s.collect(Collectors.toSet());
      System.out.println(mySet);
   }
}

Output

[MAITREE EXPRESS, BANGLADESH, TRAIN, INDIA]

In the possible approach mentioned below, we are going to implement the mySet method to demonstrate the collectors toSet() function for a stream.

Example 2

//Java code to show the implementation of Collectors toSet() function by using mySet method
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ARBRDD {
   public static void main(String[] args){
      Stream<String> s = Stream.of("10", "16", "7", "2001", "1997");
      Set<String> mySet = s.collect(Collectors.toSet());
      System.out.println(mySet);
   } 
}

Output

[1997, 16, 7, 2001, 10]

Approach 2: Use the Collector Class to Convert a set Into Another set

In these possible approaches mentioned below, we will try to use the Collector.toSet(). Here for this process, we can not put a duplicate copy of any element as well as thre is no ordering gurantee.

Example 1

//Java program to demonstrate how we can use the Collectors class to convert a set or stream of values into a Set.
package tool;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ARBRDD {
   public static void main(String[] args) {
      List<Integer> input = Arrays.asList(1, 2, 3, 4, 5, 6, 78, 9, 10, 3, 2, 34, 5,
      3);
      List<Integer> listOfIntegers = input.stream() .collect(Collectors.toList());
      System.out.println("Stream to List: " + listOfIntegers);
      ArrayList<Integer> aList = input.stream()
      .collect(Collectors.toCollection(ArrayList::new));
      System.out.println("Stream to ArrayList: " + aList);
      LinkedList<Integer> linkedList = input.stream()
      .collect(Collectors.toCollection(LinkedList::new));
      System.out.println("Stream to LinkedList: " + linkedList);
      Set<Integer> aSet = input.stream().collect(Collectors.toSet());
      System.out.println("Stream to Set: " + aSet);
      HashSet<Integer> anHashSet = input.stream()
      .collect(Collectors.toCollection(HashSet::new));
      System.out.println("Stream to HashSet: " + anHashSet);
      LinkedHashSet<Integer> aLinkedHashSet = input.stream()
      .collect(Collectors.toCollection(LinkedHashSet::new));
      System.out.println("Stream to LinkedHashSet: " + aLinkedHashSet);
      Map<Integer, String> aMap = input.stream() .collect(Collectors.toMap(
      Function.identity(), String::valueOf, (k1, k2) -> k1));
      System.out.println("Stream to Map: " + aMap);
      HashMap<Integer, String> anHashMap = input.stream() .collect(Collectors.toMap(
      Function.identity(), String::valueOf, (k1, k2) -> k1, HashMap::new));
      System.out.println("Stream to HashMap: " + anHashMap);
      LinkedHashMap<Integer, String> aLinkedHashMap = input.stream()
      .collect(Collectors.toMap( Function.identity(), String::valueOf, (k1, k2) ->
      k1, LinkedHashMap::new));
      System.out.println("Stream to LinkedHashMap: " + aLinkedHashMap);
      ConcurrentMap<Integer, String> aConcurrentMap = input.parallelStream()
      .collect(Collectors.toConcurrentMap( Function.identity(), String::valueOf, (k1,
      k2) -> k1));
      System.out.println("Stream to ConcurrentMap: " + aConcurrentMap);
      ConcurrentHashMap<Integer, String> aConcurrentHashMap = input.parallelStream()
      .collect(Collectors.toConcurrentMap( Function.identity(), String::valueOf, (k1,
      k2) -> k1, ConcurrentHashMap::new));
      System.out.println("Stream to ConcurrentHashMap: " + aConcurrentHashMap);
   }
}

Output

Stream to List: [1, 2, 3, 4, 5, 6, 78, 9, 10, 3, 2, 34, 5, 3]
Stream to ArrayList: [1, 2, 3, 4, 5, 6, 78, 9, 10, 3, 2, 34, 5, 3]
Stream to LinkedList: [1, 2, 3, 4, 5, 6, 78, 9, 10, 3, 2, 34, 5, 3]
Stream to Set: [1, 2, 34, 3, 4, 5, 6, 9, 10, 78]
Stream to HashSet: [1, 2, 34, 3, 4, 5, 6, 9, 10, 78]
Stream to LinkedHashSet: [1, 2, 3, 4, 5, 6, 78, 9, 10, 34]
Stream to Map: {1=1, 34=34, 2=2, 3=3, 4=4, 5=5, 6=6, 9=9, 10=10, 78=78}
Stream to HashMap: {1=1, 34=34, 2=2, 3=3, 4=4, 5=5, 6=6, 9=9, 10=10, 78=78}
Stream to LinkedHashMap: {1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 78=78, 9=9, 10=10,
34=34}
Stream to ConcurrentMap: {1=1, 34=34, 2=2, 3=3, 4=4, 5=5, 6=6, 9=9, 10=10,
78=78}
Stream to ConcurrentHashMap: {1=1, 2=2, 34=34, 3=3, 4=4, 5=5, 6=6, 9=9, 10=10,
78=78}

In this Java code, we are going to use an abstract map class on a data set. For this process we will take an array and after populating this array set we will refine the data with some key vaule to perform the toSet() operation.

Example 2

import java.util.AbstractMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ARBRDD{
   public static void main(String[] args){
      Map<String, String> person =
      Stream.of(
      new AbstractMap.SimpleEntry<>("Name", "[ABONI]"),
      new AbstractMap.SimpleEntry<>("Age", "[22]"),
      new AbstractMap.SimpleEntry<>("Sex", "[FEMALE]")
      ).collect(Collectors.toMap(Map.Entry::getKey,
      Map.Entry::getValue));
      for (String key: person.keySet()) {
         System.out.println(key + " OF THE PERSON IS " + person.get(key));
      }
   }
}

Output

Sex OF THE PERSON IS [FEMALE]
Age OF THE PERSON IS [22]
Name OF THE PERSON IS [ABONI]

Conclusion

toSet() collector class accumulates the input data elements into a totally a new set. Today in this article, we have learned about the toSet class present in the Java collector package. With the above mentioned algorithm, syntax; we have created some Java codes to solve the problem statement in an efficient manner.

Updated on: 27-Dec-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements