英文:
Handling multiple Lists in lambda forEach()
问题
public List<CartItem> getCartItems() {
List<CartItem> items = new ArrayList<>();
for (int ctr = 0; ctr < names.size(); ctr++) {
items.add(new CartItem(names.get(ctr), prices.get(ctr), quantities.get(ctr), subTotals.get(ctr)));
}
return items;
}
英文:
Any way to do this with lambdas/streams?
public List<CartItem> getCartItems() {
List<CartItem> items = new ArrayList<>();
for (int ctr = 0; ctr < names.size(); ctr++) {
items.add(new CartItem(names.get(ctr), prices.get(ctr), quantities.get(ctr), subTotals.get(ctr)));
}
return items;
}
答案1
得分: 1
你可以使用 IntStream
:
public List<CartItem> getCartItems() {
return IntStream.range(0, names.size())
.mapToObj(ctr -> new CartItem(names.get(ctr), prices.get(ctr), quantities.get(ctr), subTotals.get(ctr)))
.collect(Collectors.toList());
}
英文:
You can use an IntStream
:
public List<CartItem> getCartItems() {
return IntStream.range(0,names.size())
.mapToObj(ctr -> new CartItem(names.get(ctr), prices.get(ctr), quantities.get(ctr), subTotals.get(ctr)))
.collect(Collectors.toList());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论