【问题标题】:Stream reduction inner Elements流减少内部元素
【发布时间】:2019-10-20 16:36:12
【问题描述】:

我想将一个流简化为原始流的内部元素流。如果结果也是流,那将是最好的。但如果必须如此,List 也可以。

一个简单的例子是:

    private class container {
        containerLevel2 element;

        public container(String string) {
            element = new containerLevel2(string);
        }

    }
    private class containerLevel2 {
        String info;

        public containerLevel2(String string) {
            info = string;
        }

    }
public void test() {
        List<container> list = Arrays.asList(new container("green"), new container("yellow"), new container("red"));

> How can i do the following part with Streams? I want something like List<String> result = list.stream()...
        List<String> result = new ArrayList<String>();
        for (container container : list) {
            result.add(container.element.info);
        }

        assertTrue(result.equals(Arrays.asList("green", "yellow", "red")));
    }

希望你能理解我的问题。抱歉英语不好,感谢您的回答。

【问题讨论】:

    标签: java java-stream reduction


    【解决方案1】:

    Stream 只是一个处理概念。您不应将对象存储在流中。所以我更喜欢集合而不是流来存储这些对象。

    Collection<String> result = list.stream()
        .map(c -> c.element.info)
        .collect(Collectors.toList());
    

    更好的方法是在容器类中添加一个新方法,将元素信息作为字符串返回,然后在 lambda 表达式中使用该方法。这是它的外观。

    public String getElementInfo() {
        return element.info;
    }
    
    Collection<String> result = list.stream()
        .map(container::getElementInfo)
        .collect(Collectors.toList());
    

    附:您的班级名称应以大写字母开头。命名 API 元素时请遵循标准命名约定。

    【讨论】:

    • 在使用Collectors.toList() 时最好收集到List&lt;String&gt; 而不是Collection&lt;String&gt;,因为收集器结果类型本身是List&lt;T&gt;
    • 谢谢。我误解了 map() 函数。从这个名字我认为它会产生一个......地图:)
    猜你喜欢
    • 2020-11-14
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 2015-12-25
    相关资源
    最近更新 更多