Piyush Raghuwanshi
Piyush Raghuwanshi

Reputation: 47

How to set value of two or more different lists of object into one object using java 8 stream?

I want to change for loop into stream contains in main method.

This is my main method

List<Model1> list = new ArrayList<>();
                List<Model2> model = Stream.iterate(0, n -> n + 1).limit(10).map(m -> new Model2(m))
                        .collect(Collectors.toList());
                List<Model2> model2 = Stream.iterate(11, n -> n + 1).limit(10).map(m -> new Model2(m))
                        .collect(Collectors.toList());

                list.add(new Model1("a", model));
                list.add(new Model1("b", model2));


                List<Model3> list3=new ArrayList<>();
                for(Model1 m:list) {
                    for(Model2 m2: m.getModel()) {
                        Model3 m3=new Model3();
                        m3.setStr(m.getS1());
                        m3.setValue(m2.getVal());
                        list3.add(m3);
                    }
                }

                list3.stream().forEach(s-> 
                System.out.println(s.getStr()+"::"+s.getValue()));

below are my model classes

public class Model1 {

        private String s1;

        private  List<Model2> model;
        // getter setter
    }

my next model

 public class Model2 {

        private Integer val;

    //getter setter
    }

Model in which I want to set data

public class Model3 {

        private String str;
        private Integer value;
        // getter setter

    }

The output of my main method will be :

    a::0
    a::1
    a::2
    a::3
    a::4
    a::5
    a::6
    a::7
    a::8
    a::9
    b::11

I want the same output using Java streams

Upvotes: 1

Views: 1744

Answers (2)

AbdulAli
AbdulAli

Reputation: 555

If you just want to print the values without copying data into Model3 you can use the following code

list.forEach(m -> m.getModel().forEach(m2 -> System.out.println(m.getS1() + "::" + m2.getVal())))

Upvotes: 1

Hadi
Hadi

Reputation: 17289

You can do like this:

list.stream()
 .flatMap(m->m.getModel().stream().map(m2->new Model3(m.getS1(),m2.getVal())))
 .collect(Collectors.toList()); // or .collect(Collectors.toCollection(ArrayList::new))

Upvotes: 3

Related Questions