Search code examples
javajava-streamreduction

Stream reduction inner Elements


I want to reduce a stream to a stream of inner elements of the original stream. It would be the best, if the result is also a Stream. But if it had to be, a List would also work.

A simple example is:

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

I hope you can understand my question. Sorry for the bad English and thanks for your answers.


Solution

  • Stream is just a processing notion. You should not store your objects in a stream. So I would prefer collections over streams to store these objects.

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

    A much better approach is to add a new method in your container class that returns the element info as a string and then use that method in your lambda expression. Here's how it looks.

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

    P.S. Your class names should start with an upper case letter. Please follow standard naming conventions when you name API elements.