1

I have a method from an interface that goes through an array of items and buffs and calculates the sum of all of a certain method like so:

@Override public float getDamageReduction(EntityPlayable playable) { float bonus = (float) Arrays.stream(items).filter(Objects::nonNull).mapToDouble(Item::getDamageReduction(this)).sum(); float buffBonus = (float)buffs.stream().mapToDouble(Buff::getDamageReduction(this)).sum(); return bonus + buffBonus; } 

This code doesn't work because you can't Buff::getDamageReduction(this) because you're not allowed to use method references with parameters.

How can I get around this?

0

2 Answers 2

1

You can't use a method-reference in this case. You can write a lambda expression instead.

float bonus = (float) Arrays.stream(items) .filter(Objects::nonNull) .mapToDouble(item -> item.getDamageReduction(this)) .sum(); 
Sign up to request clarification or add additional context in comments.

Comments

0

You cannot use function references in this way. You could create Function outside your stream this way:

Function<Item, Double> func1 = item -> item.getDamageReduction(this); 

and respectively for the second line

Function<Buff, Double> func2 = buff -> buff.getDamageReduction(this); 

and then use it as follows:

float bonus = (float)Arrays.stream(items) .filter(Objects::nonNull) .mapToDouble(func1) .sum(); 

But I think that much simpler is just to write:

float bonus = (float)Arrays.stream(items) .filter(Objects::nonNull) .mapToDouble(item -> item.getDamageReduction(this)) .sum(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.