How to iterate over a stream from a list that has an array and return if true?

Asked

Viewed 437 times

0

How do I get the Enum object with an ID I passed as parameter check an Enum object element if true?

My builder:

private WeaponInterface(int[] weaponId, int speed,
            FightType[] fightType) {
        this.setWeaponIds(weaponId);
        this.speed = speed;
        this.fightType = fightType;
    }

What I’m trying to do :

        public static WeaponInterface forId(Item item){
        return Arrays.asList(WeaponInterface.values()).stream().
        filter(i -> i.getWeaponIds() == item.getId()).collect(n faço idéia);


    }
  • @Diego suggest to edit your question because it is not clear what you want to check with streams and post attributes and modeling of Weaponinterface and Item.

  • in view of the .collect try to use .findFirst().orElse(null) for example

  • @Brow-joe I did this, but as you can see, the weaponIds is an array and the item id is a primary, I would have to have a way to Utlilize that you said by doing something in the filter

  • Cool, I think I know what you want to do

1 answer

0


Good night, see if this resolves:

create a method to compare whether the item is present within your array

public static boolean contains(final int[] array, final int key) {
    Arrays.sort(array);
    return Arrays.binarySearch(array, key) >= 0;
}

Now just change your method forId for

public static WeaponInterface forId(Item item) {
    //Cria o predicate que irá ser aplicado dentro do filter
    Predicate<WeaponInterface> predicate = i -> contains(i.getWeaponIds(), item.getId()); 

    //Pega o array e transforma diretamente para stream
    return Arrays.stream(WeaponInterface.values())
                .filter(predicate)
                //Pega o primeiro item
                .findFirst()
                //Em caso de não encontrado retorna null
                .orElse(null);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.