繁体   English   中英

如何让所有玩家都拥有最小值

[英]How to get all players in list with min values

我正在尝试以最少的尝试回报我的游戏赢家。 但是我不确定在有平局的情况下该如何做。

我要获得胜利者是

try(Scanner scan = new Scanner(new File("result.txt"))){
                while(scan.hasNext()){
                    String[] s = scan.nextLine().split(" ");
                    players.add(new Players(s[0],s[1],Integer.valueOf(s[2])));
                }
                Collections.sort(players, Comparator.comparing((players1) -> players1.getAttempts()));
                //test// System.out.println(players);
                //Collections.sort(players, (a,b)->a.getAttempts().compareTo(b.getAttempts()));


                System.out.println("The winner is: "+ players.get(0).getName() +", with "+players.get(0).getAttempts()+ " attempt(s)!");
            }
            result.close();
}

任何帮助表示赞赏。

首先根据尝试以升序对列表进行排序

List<Players> sortedList = players.stream().sorted((a,b)->a.getAttempts().compareTo(b.getAttempts())).collect(Collectors.toList())

然后打印所有尝试次数最少的获奖者

sortedList.stream().filter(i->i.getAttempts()==sortedList.stream().findFirst()
  .get().getAttempts()).forEach(winner->System.out.println("The winners are "+winner.getvalues));

或只是流式传输按升序排序的集合对象

players.filter(i->i.getAttempts()==players.get(0).getAttempts()).forEach(winner->System.out.println("The winners are "+winner.getvalues));

这是另一种方法:

//read file into stream, try-with-resources
 try (Stream<String> stream = Files.lines(Paths.get("result.txt"))) {
            stream.map(line -> line.split("\\s"))
                  .map(a -> new Players(a[0], a[1], Integer.parseInt(a[2])))
                  .collect(groupingBy(Players::getAttemps))
                  .entrySet().stream().min(Comparator.comparingInt(Map.Entry::getKey))
                  .map(Map.Entry::getValue)
                  .map(l -> l.size() > 1 ?
                            l.stream().map(Players::getName)
                             .collect(joining(", ","there is a tie -->", 
                                     "with "+ l.get(0).getAttemps()+"attempt(s)!")) :
                           "The winner is: " + l.get(0).getName() +
                                   "with "+ l.get(0).getAttemps() +"attempt(s)!")
                  .ifPresent(System.out::println);
} catch (IOException e) { e.printStackTrace(); }

这可以处理只有一个获胜者的情况或有平局的情况,并为每个显示适当的消息。

进口:

import static java.util.stream.Collectors.*;
import java.util.stream.*;
import java.util.List;
import java.util.*;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.*; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM