Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 567
Vishal Zanzrukia Avatar asked Oct 21 '25 08:10

Vishal Zanzrukia


1 Answers

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));
like image 91
Brian Goetz Avatar answered Oct 24 '25 15:10

Brian Goetz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!