Reputation: 11
I am new to Java 8 and I want to handle multiple for loop with if clause in java 8 to update list of one objects based on the other.
Below is the code using java for each
loop. How this can be converted to java 8 streams based?
for (MonthlyData monthly : MonthlyDataList) {
for (MonthlyTsData mts : MonthlyTsDataList {
if (monthly.getMasterId() == mts.getMasterId()
&& monthly.getMasterSector() == mts.getMasterSector()
) {
mts.setFsName(monthly.getFsName());
mts.setQsName(monthly.getQsName());
break;
}
}
}
Upvotes: 0
Views: 146
Reputation: 19545
Stream API may be used for this task and the following solution is possible but it would be just a more verbose mimic of the loop-based version:
MonthlyDataList.stream()
.forEach(monthly -> {
MonthlyTsDataList.stream()
.filter(mts -> monthly.getMasterId() == mts.getMasterId()
&& monthly.getMasterSector() == mts.getMasterSector()
)
.findFirst() // Optional<MonthlyTsData>
.ifPresent(mts -> {
mts.setFsName(monthly.getFsName());
mts.setQsName(monthly.getQsName());
});
});
Upvotes: 3