0

I have ArrayList containing objects inside of it, every object in the ArrayList has a property and I wan't to see which of these objects has the lowest value on that property. Here's my code + Object structure

class ServerInfo{

   public int playerCount = 0; //This is different per every object in the array list
}

List<ServerInfo> onlineServers = new ArrayList<ServerInfo> //From this array i want object with lowest 'playerCount' property value.

2 Answers 2

1

Do it as follows:

ServerInfo elemWithMin = onlineServers.get(0);
int min = onlineServers.get(0).playerCount;
for(int i = 1; i < onlineServers.size(); i++) {
    if(onlineServers.get(i).playerCount < min) {
        min = onlineServers.get(i).playerCount;
        elemWithMin=onlineServers.get(i);
    }
}

At the end of this loop, elemWithMin will have the element with the minimum value of playerCount.

A quick test:

class Main {
    public static void main(String[] args) {
        List<ServerInfo> onlineServers = new ArrayList<ServerInfo>();
        ServerInfo si1 = new ServerInfo();
        ServerInfo si2 = new ServerInfo();
        ServerInfo si3 = new ServerInfo();
        si1.playerCount = 20;
        si2.playerCount = 10;
        si3.playerCount = 30;
        onlineServers.add(si1);
        onlineServers.add(si2);
        onlineServers.add(si3);
        ServerInfo elemWithMin = onlineServers.get(0);
        int min = onlineServers.get(0).playerCount;
        for (int i = 1; i < onlineServers.size(); i++) {
            if (onlineServers.get(i).playerCount < min) {
                min = onlineServers.get(i).playerCount;
                elemWithMin = onlineServers.get(i);
            }
        }
        System.out.println("The minimum value of payerCount: " + elemWithMin.playerCount);
    }
}

Output:

The minimum value of payerCount: 10
Sign up to request clarification or add additional context in comments.

Comments

1

You can use Java 8 stream like below :

ServerInfo serverInfoWithMinPlayerCount = onlineServers.stream().min(Comparator.comparing(ServerInfo::getPlayerCount)).orElseThrow(NoSuchElementException::new);

6 Comments

What is there is no minimum?
You can instead use .orElseThrow(NoSuchElementException::new)
That what I was suggesting - to modify your (great) answer.
I don't have function getPlayerCount , only the property.
In Object Oriented Programming, there is a concept of Encapsulation, where you would have a private attribute and a getter/setter to access it. So you can create a getter to access your private attribute.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.