views:

285

answers:

2

I'm wondering how to convert a List of one type to an array of another type in Java using Dozer. The two types have all the same property names/types. For example, consider these two classes.

public class A{
    private String test = null;

    public String getTest(){
      return this.test
    }

    public void setTest(String test){
      this.test = test;
    }
}

public class B{
    private String test = null;

    public String getTest(){
      return this.test
    }

    public void setTest(String test){
      this.test = test;
    }
}

I've tried this with no luck.

List<A> listOfA = getListofAObjects();
Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance();
B[] bs = mapper.map(listOfA, B[].class);

I've also tried using the CollectionUtils class.

CollectionUtils.convertListToArray(listOfA, B.class)

Neither are working for me, can anyone tell me what I am doing wrong? The mapper.map function works fine if I create two wrapper classes, one containing a List and the other a b[]. See below:

public class C{
    private List<A> items = null;

    public List<A> getItems(){
      return this.items;
    }

    public void setItems(List<A> items){
      this.items = items;
    }
}

public class D{
    private B[] items = null;

    public B[] getItems(){
      return this.items;
    }

    public void setItems(B[] items){
      this.items = items;
    }
}

This works oddly enough...

List<A> listOfA = getListofAObjects();
C c = new C();
c.setItems(listOfA);
Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance();
D d = mapper.map(listOfA, D.class);
B[] bs = d.getItems();

How do I do what I want to do without using the wrapper classes (C & D)? There has got to be an easier way... Thanks!

A: 

Ok, so I'm an idiot. I was too used to Dozer doing all the work for me... All I needed to do was iterate over the List of A's and create a list of B's and then convert that list to an array of B's.

Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance();
List<A> listOfA = getListofAObjects();
Iterator<A> iter = listOfA.iterator();
List<B> listOfB = new ArrayList<B>();
while(iter.hasNext()){
   listOfB.add(mapper.map(iter.next(), B.class));
}
B[] bs = listOfB.toArray(new B[listOfB.size()]);

Problem Solved!

aheu
+1  A: 

You know how many items are in listOfA before you start iterating. Why not instantiate new B[listOfA.size()] and then iterate over A, putting your new B instances directly in the array. You'll save yourself an extra iteration over all of the items in listOfB and the code will actually be easier to read to boot.

Mapper mapper = DozerBeanMapperSingletonWrapper.getInstance();

List<A> listOfA = getListofAObjects();
B[] arrayOfB = new B[listOfA.size()];

int i = 0;
for (A a : listOfA) {
    arrayOfB[i++] = mapper.map(a, B.class);
}
You're right, thanks for the suggestion.
aheu