我是Java和Android开发领域的法国初学者。其实我尝试练习,但是我被困住了...
我有一个对象(播放器)的ArrayList(playersList2),播放器包含字符串(mFirstName)和int(mScore))
我尝试了收集,循环,并且阅读了许多文档和论坛,但是我找不到解决方案,但是我敢肯定这很容易
Players players = new Players(mFirstname, mScore);
mPreferences = getSharedPreferences(PREF_PLAYERS_LIST, MODE_PRIVATE);
String fromJsonPlayersList = mPreferences.getString(PREF_PLAYERS_LIST, null);
Gson gson = new Gson();
ArrayList<Players> playersList2 = gson.fromJson(fromJsonPlayersList, new TypeToken<ArrayList<Players>>()
{
}.getType());
/* find the weakiest players/
if //mscore is bigger than weakest players
{//remove the weakest players and add this one
}*/
我想在整个ArrayList中找到最小的mScore来创建条件(如果当前的mScore>最小的playersList2用当前的Players替换最弱的PlayersList2的球员)
非常感谢
答案 0 :(得分:1)
假设这是您的Players课:
public class Players {
String mFirstName;
int mScore;
public Players(String mFirstName, int mScore){
this.mFirstName = mFirstName;
this.mScore = mScore;
}
}
这将获得最低分:
public static void main(String[] args) {
ArrayList<Players> playersList2 = new ArrayList<>();
for (int i = 0; i < 10; i++){
Players player = new Players("name", i);
}
Players lowestScore = playersList2.get(0);
for (Players p: playersList2) {
if (p.mScore < lowestScore.mScore){
lowestScore = p;
}
}
System.out.println(lowestScore.mScore);
}
答案 1 :(得分:0)
最简单的解决方案是使用简单的for循环,例如:
Players minScorePlayer = playersList2.get(0);
for (Players player: playersList2) {
if (player.getScore() < minScorePlayer.getScore()) {
minScorePlayer = player;
}
}
//now minScorePlayer variable contains the reference to a player with the minimal score
P.S。该代码旨在为您提供总体思路。您可能需要根据需要进行调整。
答案 2 :(得分:0)
有多种方法可以做到这一点。
在开始解决方案之前,让我们在这里有Player类:
class Player {
String firstName;
int score;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
一种方法是循环访问ArrayList并找到得分最低的播放器,另一种方法是使用Stream API查找得分最低的播放器。
解决方案1:在这里,我们遍历列表以查找得分最低的玩家。
List<Player> players = new ArrayList<>();
// .. add some players in the List players
Player weakestPlayer = null;
int minScore = Integer.MAX_VALUE;
for(Player player : players) {
if(player.getScore() < minScore) {
weakestPlayer = player;
}
}
解决方案2: 在Java中使用Stream API是一个有点复杂的解决方案。
Player weakestPlayer = players
.stream()
.min(Comparator.comparing(Player::getScore))
.orElseThrow(NoSuchElementException::new);
此解决方案使用Java Stream API查找得分最低的播放器。在这里,我们使用min()方法来找到得分最低的玩家。 min()方法需要一个比较器,该比较器将帮助它比较分数并确定哪个球员的分数最低。下面的代码行为int获取比较器。
Comparator.comparing(Player::getScore)
如果列表为空,则将找不到一个得分最低的球员,这将引发错误。