Reputation: 3219
I'm building e-commerce application and i have one case scenario where i need to cross out sizes which are not available in store.
I have fixed arraylist of strings with sample like this: "36", "38", "40", "42"
and i have available sizes with sample like this: "36", "38", "40"
Now i need to iterate through first array and cross out those sizes which are not available.
Here is one part of code where i'm doing that:
// tempSizes - available sizes
// mProduct.getSizes() - all sizes
for (String tempSize : tempSizes) {
for (int i = 0; i < mProduct.getSizes().size(); i++) {
if (tempSize.equals(mProduct.getSizes().get(i))) {
// if size is available
sizes.add(new Size(mProduct.getSizes().get(i), true));
} else {
// if size is not available
sizes.add(new Size(mProduct.getSizes().get(i), false));
}
}
}
Problem here is that nested for loop will be called three times and the result will output with duplicates of sample. If there is an easier way to do this, please let me know, i would appreciate it.
Upvotes: 0
Views: 72
Reputation: 10877
Try this code
// mProduct.getSizes() - all sizes
for (int i = 0; i < mProduct.getSizes().size(); i++) {
int prodSize = mProduct.getSizes().get(i);
boolean sizeFound = false;
// tempSizes - available sizes
for (String tempSize : tempSizes) {
if (tempSize.equals(mProduct.getSizes().get(i))) {
// if size is available
sizes.add(new Size(prodSize, true));
sizeFound = true;
break;
}
}
if(sizeFound == false){
// if size is not available
sizes.add(new Size(mProduct.getSizes().get(i), false));
}
}
Upvotes: 1
Reputation: 30809
You can easily do it with ArrayList
using one for
loop, e.g.:
List<Integer> samples = Arrays.asList(36, 38, 40 ,42);
List<Integer> available = Arrays.asList(36, 38, 40);
List<Integer> unavailable = new ArrayList<>();
for(int size : samples){
if(!available.contains(size)){
unavailable.add(size);
}
}
System.out.println(unavailable);
This will iterate through all the samples, check whether they are available and if not, put them into anoter list. If you have arrays, you can use Arrays.asList()
method to convert them into the Lists.
Upvotes: 3