I have a class containing two properties:
public class player{
public player(String playerName,int points){
this.playerName=playerName;
this.points=points;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
private String playerName;
private int points;
}
I have arrayList class contains collection of palyer objects.
List palyers=new ArrayList();
players.add(new player("mike",2));
players.add(new player("steve",3));
players.add(new player("jhon",7));
players.add(new player("harry",5);
Here my question is how to display player names with smallest points difference.
Output:
Based on the example code i written:
Mike and steve is the output
THis way comparison should happen:
mike to steve --> 1
mike to jhon--->5
mike to harry-->3
steve to mike -->1
steve to jhon--->5
steve to harry--->3
jhon to mike-->5
jhon to steve-->4
jhon to harry--->2
harry to mike -->3
harry to steve-->2
harry to jhon -->2
Based on above comparison mike and steve should display
Any java API to compare the properties?
So you want to know the pair of players whose score has the smallest difference?
I don’t think there’s an API function for that, although there might be something in the Apache Commons Collections.
Otherwise you’ll have to use a nested loop.
Obviously, this code needs some work; for example, if two pairs of players have the same difference between them, only the latest pair processed will be reported. You may also want to re-work this piece of code to remove the default values (Note how the
System.out.printlnwill crash if your List contains 0 players, for example). I leave these for you to solve. HTH.