Foreach in a foreach removing items from list

Tom van den Bogaart :

I am creating a Java application based on who is it ?. Now I'm making a method where I want the other cards when a question is answered.

I have two lists:

A list is an ImageView list in which I have 24 image views that the cards must represent.

The other list is a list of 24 map objects.

Now I want to remove ImageViews from the ImageView list if an ID of an image view is the same as the name of a card in an ImageView.

I tried to do a foreach in a foreach and then remove an item from the list but I couldn't figure it out.

The method I created:

public List<ImageView> getImageViews(List<Card> newCards){

    for (ImageView imageView: new ArrayList<>(allCards)) {
        String imageName = imageView.getId().toLowerCase();

        for (Card card: new ArrayList<>(newCards)){
            String cardName = card.getName().toLowerCase();

            if (!imageName.equals(cardName)){
                allCards.remove(imageView);
            }
        }
    }

    return allCards;
}
davidxxx :

Some pointers :

1) allCards.remove(imageView); will work only if equals() is overrided in ImageView consequently

2) This means that you want to remove the card if the join elements don't match :

if (!imageName.equals(cardName)){
    allCards.remove(imageView);
}

You will remove the element only when it matches while you said :

Now I want to remove ImageViews from the ImageView list if an ID of an image view is the same as the name of a card in an ImageView.

Something in this way would be better :

if (imageName.equals(cardName)){
    allCards.remove(imageView);
    break; // to go back to the outer loop
}

With Iterator you could make things more simple and without relying on equals() overriding :

public List<ImageView> getImageViews(List<Card> newCards){
    for (Iterator<ImageView> imageViewIt = allCards.iterator(); imageViewIt.hasNext();) {
        ImageView imageView = imageViewIt.next();
        String imageName = imageView.getId().toLowerCase();
        for (Card card: newCards){
            String cardName = card.getName().toLowerCase();
            if (imageName.equals(cardName)){
                imageViewIt.remove();
                break;
            }
        }
    }
    return allCards;
}

And with Java 8 you could even do that :

public List<ImageView> getImageViews(List<Card> newCards){
    allCards.removeIf(view -> 
                       newCards.anyMatch(card -> 
                                card.getName().equalsIgnoreCase(view.getId())
                     );
   return allCards;
}

This code works.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156119&siteId=1