过滤嵌套列表并使用 Java8 中的流进行转换
Filter nested lists and trasnform with streams in Java8
我必须列出对象。我想在 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;
}
下面java8中的代码如何使用流来避免嵌套循环?
谢谢!
您可以使用 forEach 并使用 filter
作为对象属性的条件
public List<CarDto> transformData(List<CarDto> listDataA,List<CarDto> listDataB){
List<CarDto> fusionList = new ArrayList<CarDto>();
listDataA.stream()
.filter(Objects::nonNull)
.forEach(objA-> listDataB.stream()
.filter(Objects::nonNull)
.filter(objB-> objA.getKey1().equals(objB.getKey1()))
.filter(objB-> objA.getKey2().compareTo(objB.getKey2()) == 0)
.filter(objB-> objA.getKey3().equals(objB.getKey3()))
.forEach(objB->fusionList.add(this.fusionDataAB(objA, objB))));
return fusionList;
}
我必须列出对象。我想在 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;
}
下面java8中的代码如何使用流来避免嵌套循环?
谢谢!
您可以使用 forEach 并使用 filter
作为对象属性的条件
public List<CarDto> transformData(List<CarDto> listDataA,List<CarDto> listDataB){
List<CarDto> fusionList = new ArrayList<CarDto>();
listDataA.stream()
.filter(Objects::nonNull)
.forEach(objA-> listDataB.stream()
.filter(Objects::nonNull)
.filter(objB-> objA.getKey1().equals(objB.getKey1()))
.filter(objB-> objA.getKey2().compareTo(objB.getKey2()) == 0)
.filter(objB-> objA.getKey3().equals(objB.getKey3()))
.forEach(objB->fusionList.add(this.fusionDataAB(objA, objB))));
return fusionList;
}