Java: convert classA collection to classB collection

Given the list of Foo myFoos, I need to map them to a collection of another class, like Bar. Now I do it like this:

List<Bar> myBars = new...
for(Foo f : foos) {
    Bar b = new Bar();
    b.setAProperty(f.getProperty);
    b.setAnotherProp(f.getAnotherProp);
    myBars.add(b);
}

So, is there an easier way to do this? Of course, this is pretty easy, but I wonder if there is any magic out there that would turn foos into bars without having to manually browse through the list, especially because my input list could be large.
If not, did you know, did you know the compiler to optimize this? My main concern is performance.

Thank!

- Llappall Page

+3
source share
4 answers

You cannot just not go on the list, because you need to convert each element!

, Bar, Foo. :

for(foo f : foos) {
    myBars.add(new Bar(f));
}

Bar. Foo.getAsBar(), Bar . , , .

+7
public Bar(Foo f){
  this.a = f.a;
  this.b = f.b;
}



for (Foo f : myFoos){
  myBars.add(new Bar(f));
}
+2

, , :

, Foo Bar , Bar, Foo getters.

  • , / Bar .
  • , / Bar .

public class Bar {
  Foo foo;
  public Bar(Foo foo) {
      this.foo = foo;
  }
  public int getPropertyA() {
      return foo.getPropertyA();
  }
  public int getAnotherProperty() {
      return foo.getAnotherProperty();
  }
}

>

Foos . .

0

, - .

()

: Foo Bar .

  • Foo Bar , Properties.
  • Properties Foo Bar.
  • Bar Foo, Foo Bar.

:

  • No need to create copies of properties

Minuses:

  • The set of properties must be the same for Foo and Bar
  • Additional Indirection (= Overhead) on Access to Property
  • Changes to Bar properties affect the original properties of Foo.


    public class Properties {
        public int getPropertyA() {..}
        public int getAnotherProperty() {..}
    }
    public class Foo {
        Properties properties;
        public Foo(Properties properties)
            this.properties = properties;
        }
        public Properties getProperties() {
            return properties;
        }
    }
    public class Bar {
        Properties properties;
        public Foo(Properties properties)
            this.properties = properties;
        }
        public Properties getProperties() {
            return properties;
        }
    }
    //Client code:
    //Access properties:
    int i = foo.getProperties().getPropertyA();
    //Map Foos to Bars
    for (Foo foo: foos) {
        Bar bar = new Bar(foo.getProperties());
        //Do something with bar
    }
0
source

All Articles