【发布时间】:2021-05-05 13:27:02
【问题描述】:
我必须列出对象。我想在 ListB 中找到 ListA 的关键元素,然后调用一个融合数据的函数。我有这个:
public List<CarDto> transformData(List<CarDto> listDataA,List<CarDto> listDataB){
List<CarDto> fusionList = new ArrayList<CarDto>();
for(CarDto carDtoDataA:listDataA) {
for(CarDto carDtoDataB:listDataB) {
if(null != carDtoDataA && null != carDtoDataB
&& carDtoDataA.getKey1().equals(carDtoDataB.getKey1())
&& 0==carDtoDataA.getKey2().compareTo(carDtoDataB.getKey2())
&& carDtoDataA.getKey3().equals(carDtoDataB.getKey3())) {
fusionList.add(this.fusionDataAB(carDtoDataA,carDtoDataB));
}
}
}
return fusionList;
}
如何使用流在java 8中编写下面的代码以避免嵌套循环?
谢谢!
【问题讨论】:
-
你的
getKey2()对象不覆盖等于吗?它会比 compareTo (imho) 更清楚一些。 -
虽然这是一个
O(A*B)解决方案,但groupingBy在listDataA和listDataB中使用Arrays.as(k1, k2, k3)的max(O(A), O(B))运行时方法将为您提供Maps 进行迭代通过一个并在恒定时间内查找另一个以将元素添加到fusionList。 ** 你想在这里实现平等吗0 == dataA.getKey2().compareTo(dataB.getKey2())?
标签: list java-8 java-stream nested-loops