【问题标题】:stream list into a set流列表成一个集合
【发布时间】:2015-12-13 00:17:25
【问题描述】:

我希望重构我在某些代码中使用流的方式。第一个例子是我目前是如何做到的。第二个例子是我试图让它看起来像什么。

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

【问题讨论】:

  • 您需要先映射 Stream 元素,然后再将它们收集到 Set 中。 someDao.findByType(type) .stream().map(TheClass::getValue).collect(toSet());

标签: java collections lambda java-8 java-stream


【解决方案1】:

使用Collectors.toSet

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

【讨论】:

    猜你喜欢
    • 2018-07-24
    • 1970-01-01
    • 2020-01-05
    • 2019-04-11
    • 2015-10-20
    • 2014-04-21
    • 2012-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多