Check If List Contains All Elements Of An Array [closed] Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Check If List Contains All Elements Of An Array [closed] without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to check if a List contains all values that are saved in an Array.

Here is my code:

List<PlayingCard> playerDeck = new ArrayList<>();
playerDeck.add(PlayingCard.METAL);
playerDeck.add(PlayingCard.METAL);

public boolean canBuild(Item item) {
    return playerDeck.containsAll(Arrays.asList(item.requiredCards()));
}
public enum Item {
    ...

    public PlayingCard[] requiredCards() {
        return new PlayingCard[] {
            PlayingCard.METAL,
            PlayingCard.METAL,
            PlayingCard.METAL
        };
    }
}

My current canBuild() method won’t work like this.

playerDeck = [Metal] requiredCards = [Metal, Metal]
playerDeck.containsAll(requiredCards) == true

Can anybody help me out?

Answer

You didn’t declare one of your enums correctly. And it is unclear whether you were trying to executed method in a static context. Try the following:

enum PlayingCard {
    METAL
}

enum Item {
    FOO;

    public PlayingCard[] requiredCards() {
        return new PlayingCard[] { PlayingCard.METAL,
                PlayingCard.METAL, PlayingCard.METAL };
    }
}

static List<PlayingCard> playerDeck = new ArrayList<>();

public static void main(String[] args) {

    playerDeck.add(PlayingCard.METAL);
    playerDeck.add(PlayingCard.METAL);
    Item foo = Item.FOO;
    System.out.println(canBuild(foo));

}

public static boolean canBuild(Item item) {
    return playerDeck
            .containsAll(Arrays.asList(item.requiredCards()));
}

UPDATE:

 List<Integer> a = List.of(1,1,1);
 List<Integer> b = List.of(1,1);
 List<Integer> c = List.of(1,1,1);
 List<Integer> d = List.of(1,2,1);
 List<Integer> e = List.of(1,1,2);
 System.out.println(a.equals(b)); //false different count
 System.out.println(a.equals(c)); //true same numbers and count
 System.out.println(a.equals(d));// false same count, different numbers
 System.out.println(a.equals(e)); // false same numbers and count, different order
We are here to answer your question about Check If List Contains All Elements Of An Array [closed] - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji