Return the object from the array with the highest value?
I am trying to return an object from an arraylist I have that contains different opponents for my text combat game. Opponents in an arraylist have different "deadlylevels" to separate one light opponent from a tough one.
Explain it differently; Let's say I have three opponents in my Arrayist and they have dead levels of 30, 40 and 50 respectively. I want to return the deadliest of them all, so it would be a dead level 50 enemy.
I already gave them different dead levels, but I'm not sure how to get the opponent with the highest dead level back.
source to share
If you want the max level, it will just be max (). But you need a maximum level opponent. In Eclipse Collections we call this template maxBy()
. If you can replace ArrayList
with MutableList
, then it will look like this:
MutableList<Opponent> opponents = ...;
Opponent opponent = opponents.maxBy(Opponent::getDeadlyLevel);
If you cannot or will not convert ArrayList
, you can still use the static utility on Iterate
.
Opponent opponent = Iterate.maxBy(opponents, Opponent::getDeadlyLevel);
You can use Collections.max()
together with Comparator.comparing()
for assembly Comparator
.
Opponent opponent =
Collections.max(opponents, Comparator.comparing(Opponent::getDeadlyLevel));
Or you can use Java 8 streams.
Optional<Opponent> optionalOpponent =
opponents.stream().max(Comparator.comparing(Opponent::getDeadlyLevel));
Opponent opponent = optionalOpponent.get(); // If you're sure there at least one
Note: I am a committer for Eclipse collections.
source to share
Use Stream#max()
by providing a function for the corresponding attribute:
List<Fighter> list; // given a list of Fighters
Fighter deadliest = list.stream()
.max((a,b) -> a.getDeadlyLevel() - b.getDeadlyLevel())
.get();
source to share
Use Comparator.comparing
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class DeathMatch {
public static void main(String[] arg){
List<Opponent> list = Arrays.asList(new Opponent("ZZ",10),new Opponent("WW",50),new Opponent("MM", 30));
Opponent deadliest = list.stream().max(Comparator.comparing(p->p.getLevel())).get();
System.out.println(deadliest.getName()+","+ deadliest.getLevel());
}
}
source to share