What is the default Set/List implementation with C

2020-03-07 06:34发布

问题:

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

回答1:

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