有 Java 编程相关的问题?

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

java使用lambdas从2个现有对象创建新对象,将ArrayList字段中不同对象的各种值相加

我有这个豆子,我的豆子。MyBean包含两个ComplexObject列表,每个列表都有SimpleObject列表,其中有一个简单的int字段(field1)

我想做的是取2个MyBean对象——除了SimpleObject中的值之外,它们完全相同。字段1字段--
使用lambdas/mapTo/reduce/whatever,对每个int字段(field1)求和,并用新的和创建一个新的MyBean,但按原样维护其余字段(列表)

我的对象如下所示:

public class MyBean {
  private ArrayList<ComplexObject1> list1 = new ArrayList<>();
  private ArrayList<ComplexObject2> list2 = new ArrayList<>();
}

public class ComplexObject1 {
  private ArrayList<SimpleObject1> list1 = new ArrayList<>();
}

public class ComplexObject2 {
  private ArrayList<SimpleObject1> list1 = new ArrayList<>();
}

public class SimpleObject1 {
  private int field1;
}

public class SimpleObject2 {
  private int field1;
}

我对lambdas几乎没有经验,但我希望我能在这里使用它们。我只是不知道该怎么做。我知道如何在不同对象的字段中使用lambdas求和值,但我不知道如何使用这些求和创建新对象,因为它们位于子对象中

非常感谢任何帮助


共 (1) 个答案

  1. # 1 楼答案

    您的数据模型基本上与List<List<Integer>>相同。所以,如果我理解正确的话,你想做一个这样的新列表,将另外两个列表的内部列表的元素相加

    测试数据:

    // [[1, 2, 3], [4, 5, 6, 7]]
    List<List<Integer>> list1 = 
      new ArrayList<>(Arrays.asList(Arrays.asList(1,2,3), Arrays.asList(4,5,6,7)));
    // [[10, 20, 30], [40, 50, 60, 70]]
    List<List<Integer>> list2 = 
      new ArrayList<>(Arrays.asList(Arrays.asList(10,20,30), Arrays.asList(40,50,60,70)));
    

    新的列表将是list3

    List<List<Integer>> list3 = new ArrayList<>();
    
    List<Integer> tmp = new ArrayList<>();
    for (int i = 0; i < list1.size(); i++){
        for (int j = 0; j < list1.get(i).size(); j++){
            tmp.add(list1.get(i).get(j) + list2.get(i).get(j));
        }
        list3.add(new ArrayList<>(tmp));
        tmp.clear();
    }
    

    现在包含[[11, 22, 33], [44, 55, 66, 77]]

    我将把它留给你们,让你们根据List<ComplexObject>List<SimpleObject>的情况来重写


    无法阅读的“streamy”解决方案:

    list3 = new ArrayList<>(
    Stream.of(list1, list2)
      .flatMap(x -> IntStream.range(0,x.size()).mapToObj(index -> new SimpleEntry<>(index, x.get(index))))
      .collect(Collectors.collectingAndThen(
                Collectors.toMap(   SimpleEntry::getKey, 
                                    SimpleEntry::getValue, 
                                    (a, b) -> {return IntStream.range(0, a.size())
                                                        .mapToObj(index -> a.get(index) + b.get(index))
                                                        .collect(Collectors.toList());})
              , Map::values)));
    

    这将产生与第一个解决方案相同的结果