Java 8 Stream API中使用Collector的默认Set/List实现是什么? [英] What is the default Set/List implementation with Collectors in Java 8 Stream API?

查看:194
本文介绍了Java 8 Stream API中使用Collector的默认Set/List实现是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java 8中具有以下代码捕捉功能.

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

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

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

还有,有什么方法可以告诉Java API使用特定的实现(例如HashSet)?

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

推荐答案

toSet()收集器未指定其使用的实现;您得到一个Set,仅此而已.

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

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

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

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

这篇关于Java 8 Stream API中使用Collector的默认Set/List实现是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆