Wangensteen
Wangensteen

Reputation: 75

Return object from arraylist with highest value?

I'm trying to return an object from an arraylist I have, which contains different opponents for my text-based fighting game. The opponents in the arraylist have different "deadlylevels", to seperate one easy opponent from a tough one.

To explain it differently; Let's say I have three opponents in my arraylist, and they have the deadlylevels of 30, 40 and 50, respectively. I want to return the most deadliest of them, so that would be the opponent who has a deadlylevel of 50.

I have already given them different deadlylevels, but I'm not sure how to return the opponent that has the highest deadlylevel.

Upvotes: 3

Views: 1119

Answers (4)

Craig P. Motlin
Craig P. Motlin

Reputation: 26740

If you wanted the maximum level, that would just be max(). But you want the max opponent, by level. In Eclipse Collections, we call that pattern maxBy(). If you can replace your ArrayList with MutableList then it becomes:

MutableList<Opponent> opponents = ...;
Opponent opponent = opponents.maxBy(Opponent::getDeadlyLevel);

If you can't or won't convert the ArrayList, you can still use static utility on Iterate.

Opponent opponent = Iterate.maxBy(opponents, Opponent::getDeadlyLevel);

You could use Collections.max() along with Comparator.comparing() to build the Comparator.

Opponent opponent =
    Collections.max(opponents, Comparator.comparing(Opponent::getDeadlyLevel));

Or you could use Java 8 Streams.

Optional<Opponent> optionalOpponent = 
    opponents.stream().max(Comparator.comparing(Opponent::getDeadlyLevel));
Opponent opponent = optionalOpponent.get(); // If you're sure there's at least one

Note: I am a committer for Eclipse Collections.

Upvotes: 6

zawhtut
zawhtut

Reputation: 8561

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());
    }
}

Upvotes: 1

Bohemian
Bohemian

Reputation: 425083

Use Stream#max() providing a function for the relevant attribute:

List<Fighter> list; // given a list of Fighters
Fighter deadliest = list.stream()
    .max((a,b) -> a.getDeadlyLevel() - b.getDeadlyLevel())
    .get();

Upvotes: 3

user4668606
user4668606

Reputation:

Create a Comparator that compares the levels of the oponents and use Collections.max(oponentList , theComparator).

Upvotes: 4

Related Questions