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

0

How do I get the enum object with an ID that I passed as a parameter to check an element of the enum object 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);


    }
    
asked by anonymous 07.04.2017 / 00:42

1 answer

0

Good night, see if this solves:

create a method to compare if the item is present inside 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 to

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);
}
    
09.04.2017 / 02:13