有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用Dozer将一种类型的列表转换为另一种类型的数组

我想知道如何在Java中使用Dozer将一种类型的列表转换为另一种类型的数组。这两种类型具有所有相同的属性名称/类型。 例如,考虑这两个类。

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;
    }
}

我试过了,运气不好

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

我也尝试过使用CollectionUtils类

CollectionUtils.convertListToArray(listOfA, B.class)

他们都不为我工作,谁能告诉我我做错了什么?地图绘制者。如果我创建两个包装器类,一个包含一个列表,另一个包含一个b[],map函数就可以正常工作。见下文:

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;
    }
}

这很奇怪

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

如何在不使用包装类(C&D)的情况下完成我想做的事情?一定有更简单的方法。。。 谢谢


共 (3) 个答案

  1. # 1 楼答案

    在开始迭代之前,您知道列表中有多少项。为什么不实例化新的B[listOfA.size()],然后在A上迭代,将新的B实例直接放入数组中呢。您将在listOfB中的所有项目上为自己节省一次额外的迭代,代码实际上将更易于阅读和引导

    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);
    }
    
  2. # 2 楼答案

    好吧,所以我是个白痴。我太习惯了推土机帮我做所有的工作。。。我所需要做的就是迭代A的列表,创建一个B的列表,然后将该列表转换为一个B的数组

    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()]);
    

    问题解决了

  3. # 3 楼答案

    如果我能写下面的代码并且它能正常工作,这将更有意义

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