关于删除foreach循环并将其转换为流,我还有另一个问题。我将在这里张贴整个方法,以防有更多的信息需要,而不仅仅是foreach循环。我已经尝试用平面地图做了,但这并不能解决我的问题。我希望你们中的一些人能帮助我!我会很感激的!
public void handlePickedOrders(final List<PickOrder> pickedOrders) {
Contract.requires(pickedOrders != null, "illegal argument");
// Your code goes here - if needed
if (error) {
new Scanner(System.in).nextLine();
}
if (!pickedOrders.isEmpty()) {
Map<String, Integer> removedProducts = pickedOrders.stream()
.flatMap(n -> n.getPickOrderLines().stream())
.collect(Collectors.toMap(s -> s.getProductCode(),
p -> p.getQuantity(),
(a1, a2) -> a1 + a2));
//Problem area
for (Map.Entry<String, Integer> entry : removedProducts.entrySet()) {
if (error) {
System.out.println("Remove " + entry.getValue() + " pieces of " + entry.getKey());
}
quantityOnHand.replace(entry.getKey(), quantityOnHand.get(entry.getKey()) - entry.getValue());
}
if (error) {
System.out.println("Remove Pick Orders " + pickedOrders + " from Queue");
}
pickOrders.removeAll(pickedOrders);
for (PickOrder pickOrder : pickOrders) {
for (String productCode : removedProducts.keySet()) {
if (pickOrder.containsProduct(productCode)) {
pickOrder.calcReplenishmentsNeeded(quantityOnHand);
if (error) {
System.out.println("Recalculating: " + pickOrder);
}
break;
}
}
}
}
}
虽然我没有得到确切的问题声明,但您可以尝试这种嵌套的foreach循环,可能您正在寻找。我希望它能帮助你。
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static void main(String[] args) {
List<PickOrder> pickedOrders = Arrays.asList(
new PickOrder("pc1",1000),
new PickOrder("pc2",2000),
new PickOrder("pc3",3000),
new PickOrder("pc4",4000),
new PickOrder("pc5",5000)
);
List<PickOrder> pickOrders = Arrays.asList(
new PickOrder("pc6",6000),
new PickOrder("pc7",7000),
new PickOrder("pc8",8000)
);
Map<String, Integer> removedProducts = new HashMap<>();
removedProducts.put("pc1",1000);
removedProducts.put("pc2",2000);
removedProducts.put("pc3",3000);
pickOrders.forEach( pickOrder -> removedProducts.keySet().forEach(rp -> {
if(pickOrder.getProductCode().equals(rp)) {
//pickOrder.calcReplenishmentsNeeded(quantityOnHand);
/*if (error) {
System.out.println("Recalculating: " + pickOrder);
}*/
}
}));
}
PickOrder.java
public class PickOrder {
private String productCode;
private int quantity;
public PickOrder(String productCode, int quantity) {
this.productCode = productCode;
this.quantity = quantity;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
Girdhar