什么是Java 8 Stream API中的收集器的默认Set/List实现?

Vis*_*kia 2 java-8 java-stream collectors

我在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());
Run Code Online (Sandbox Code Playgroud)

我只是想知道Set它在使用时使用默认的哪个实现Collectors.toSet()(参见上面的例子)?

另外,有没有办法表明java API使用特定的实现(例如HashSet)?

Bri*_*etz 5

toSet()回收不指定要使用的执行情况; 你得到了一个Set,就是这样.

如果您需要特定类型的集合,请使用toCollection()并为您的集合提供工厂方法:

    ...collect(Collectors.toCollection(HashSet::new));
Run Code Online (Sandbox Code Playgroud)