I have given two list In the list if the value and position matches with the other one then they retain the value else should be displayed as empty.`
Input – Cart 1: [“Sugar”, “Bread”, “Juice”, “Soda”, “Flour”]
Cart 2: [“Sugar”, “Bread”, “Butter”, “Cheese”, “Fruit”]
Expected Output-
Output Cart 1: [“Sugar”, “Bread”, “Juice”, “Soda”, “Flour”, “”, “”, “”]
Output Cart 2: [“Sugar”, “Bread”, “”, “”, “”,”Butter”, “Cheese”, “Fruit”]
public static List<String> mergeShoppingCarts(List<String> cart1, List<String> cart2) {
int maxItems = Math.max(cart1.size(), cart2.size());
List<String> mergedCart1 = new ArrayList<>(maxItems);
List<String> mergedCart2 = new ArrayList<>(maxItems);
for (int i = 0; i < maxItems; i++) {
if (i < cart1.size()) {
mergedCart1.add(cart1.get(i));
} else {
mergedCart1.add("");
}
if (i < cart2.size()) {
mergedCart2.add(cart2.get(i));
} else {
mergedCart2.add("");
}
if (i < cart1.size() && i < cart2.size() && cart1.get(i).equals(cart2.get(i))) {
mergedCart2.set(i, "");
}
}
return mergedCart1;
}
I’m not getting this as output
Merged Cart 1: [Sugar, Bread, Juice, Soda, Flour]
Merged Cart 2: [Sugar, Bread, Butter, Cheese, Fruit]
Please help me in solving this issue.
dhiral is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2