Search code examples
java-8java-streamcollectors

What is the default Set/List implementation with Collectors in Java 8 Stream API?


I have below code snap with Java 8.

 List<Employee> employees = DataProvider.getEmployees();
 Set<Employee> set = employees.stream().filter(emp -> {
                System.out.println(emp.getName());
                return emp.getName().equals("Vishal");
            }).collect(Collectors.toSet());

I just want to know which implementation of Set it is using by default when we use Collectors.toSet() (refer above example)?

Also, is there any way to tell the Java API to use a particular implementation (for example, HashSet)?


Solution

  • The toSet() collector does not specify which implementation it uses; you get a Set, that's all.

    If you want a specific kind of set, use toCollection() and provide a factory method for your set:

        ...collect(Collectors.toCollection(HashSet::new));