0

I have 2 POJO Foo and FooDBObj, I fetch List of FooDBObj from database and now I need to create List of Foo Objects. I need to set Id and name in FooDBObj into Foo's BarId and BarName respectively. If its in Java Stream it will be better

I have tried to get the list of Id's alone from below code.

List<String> fooIds =FooDBObjList.stream().map(FooDBObj::getId).collect(Collectors.toList());

The above code can give me only list of Id for Foo I need all the FooDBObj.id to be set in Foo.BarId and FooDBObj.name to be set in FooDBObj.BarName

kk.
  • 3,747
  • 12
  • 36
  • 67
Kishore Chandran
  • 457
  • 4
  • 12
  • I think that Link is usefull for you. https://stackoverflow.com/questions/19760590/how-to-copy-properties-from-a-bean-to-another-bean-in-different-class – Govind Sharma Jun 12 '19 at 09:46
  • Because `FooDBObj::getId` don't create a different instance but just extract the ID. Use a method to create a `Foo` instance from a `FooDBObj`. – AxelH Jun 12 '19 at 09:46

4 Answers4

3

I guess you could simply write the mapping logic directly:

Stream<Foo> = fooDBObjList.stream()
  .map(db -> {
    Foo foo = new Foo();
    foo.setBarId(db.Id);
    foo.setBarName(db.name);

    return foo;
  });

If Foo already have an appropriate constructor (or a factory method like Foo.from(FooDbObj) it could be done via method reference:

Stream<Foo> = fooDbObjList.stream().map(Foo::from); // Factory method
….map(Foo::new) // if Foo(FooDbObj) constructor
….map(db -> new Foo(db.Id, db.name)) // if Foo(barId, barName) constructor
jensgram
  • 31,109
  • 6
  • 81
  • 98
1

Or you can go like this too,

fooDBObjList.stream().forEach(x -> {
            Foo foo = new Foo ();
            foo.setId(x.getid());
            foo.setName(x.getname());   
            foooList.add(foo);
        });
Mak
  • 1,068
  • 8
  • 19
0
fooDBObjList.stream()
    .map(Foo:map)
    .collect(Collectors.toList());

in Foo class:

Foo map(FooDBObj dbObj) {
   return Foo.builder
              .id(dbObj.getId())
              .name(dbObj.getName())
              .build();
}
erolkaya84
  • 1,769
  • 21
  • 28
-1
One can use below snippet:


  List foo = FooDBObjList.stream().map(fooDBObj -> { Foo f = new Foo();
                                                          f.setBarName(fooDBObj.getName());
                                                          f.setBarId(fooDBObj.getId()); 
                                                          return f;}).collect(Collectors.toList());