将流列表转换为集合

49

我希望重新设计我在代码中使用流的方式。第一个例子是我目前使用的方式,第二个例子是我试图让它看起来像什么。

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

2
在将元素收集到Set之前,您需要映射Stream元素。 someDao.findByType(type) .stream().map(TheClass::getValue).collect(toSet()); - Alexis C.
1个回答

86

使用 Collectors.toSet

Set<String> results = someDao.findByType(type)
        .stream()
        .map(ClassName::getValue)
        .collect(Collectors.toSet());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接