我正在寻找重构如何在我的一些代码中使用流.第一个例子是我目前的做法.第二个例子是我试图让它看起来像.
- Set<String> results = new HashSet<String>();
- someDao.findByType(type)
- .stream()
- .forEach(t-> result.add(t.getSomeMethodValue()) );
看起来像这样吗?如果是这样,我该怎么做呢?
- Set<String> results = someDao.findByType(type)
- .stream()
- .collect( /* ?? no sure what to put here */ );
解决方法
使用Collectors.toSet:
- Set<String> results = someDao.findByType(type)
- .stream()
- .map(ClassName::getValue)
- .collect(Collectors.toSet());