Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8: Stream map two properties in the same stream

I have a class Model with the following signature:

class Model {
        private String stringA;
        private String stringB;

        public Model(String stringA, String stringB) {
            this.stringA = stringA;
            this.stringB = stringB;
        }

        public String getStringA() {
            return stringA;
        }

        public String getStringB() {
            return stringB;
        }
}

I would like to map a List<Model> to a List<String> containing both stringA and stringB in a single stream

List<String> strings = models.stream()
                .mapFirst(Model::getStringA)
                .thenMap(Model::getStringB)
                .collect(Collectors.toList());

or:

List<String> strings = models.stream()
                .map(Mapping.and(Model::getStringA,Model::getStringB))
                .collect(Collectors.toList());

Of course none of them compiles, but you get the idea.

Is it somehow possible?

Edit:

Example:

Model ab = new Model("A","B");
Model cd = new Model("C","D");
List<String> stringsFromModels = {"A","B","C","D"};
like image 923
Sunflame Avatar asked Mar 29 '18 10:03

Sunflame


1 Answers

You can have a list of all the values one after another like so:

List<String> resultSet =
               modelList.stream()
                        .flatMap(e -> Stream.of(e.getStringA(), e.getStringB()))
                        .collect(Collectors.toList());

The function passed to flatMap will be applied to each element yielding a Stream<String>. The use of flatMap is necessary here to collapse all the nested Stream<Stream<String>> to a Stream<String> and therefore enabling us to collect the elements into a List<String>.

like image 162
Ousmane D. Avatar answered Oct 02 '22 08:10

Ousmane D.