流减少内部元素

问题描述 投票:0回答:1

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

一个简单的例子是:

    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")));
    }

希望您能理解我的问题。对不起,英语不好,谢谢您的回答。

lambda java-8 stream java-stream reduction
1个回答
0
投票

流只是一个处理概念。您不应将对象存储在流中。因此,与流相比,我更喜欢使用集合来存储这些对象。

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());
© www.soinside.com 2019 - 2024. All rights reserved.