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

时间:2018-11-17 03:57:05

标签: java java-8

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

我要获得胜利者是

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

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

这是另一种方法:

//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.*;