Java 如何使用最小值获取列表中的所有玩家
我试图以最低的尝试回报我比赛的赢家。但我不确定如何在打成平局的情况下做到这一点 我的目标是获得优胜者Java 如何使用最小值获取列表中的所有玩家,java,java-8,Java,Java 8,我试图以最低的尝试回报我比赛的赢家。但我不确定如何在打成平局的情况下做到这一点 我的目标是获得优胜者 try(Scanner scan = new Scanner(new File("result.txt"))){ while(scan.hasNext()){ String[] s = scan.nextLine().split(" "); players.add(new Player
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())
或者简单地流式处理按升序排序的集合对象
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(); }
在平局时需要做什么?显示第一名有平局,然后列出玩家的姓名,以及尝试在
新玩家(s[0],s[1],Integer.valueOf(s[2])中哪些属性及其对应的类型
?另外,基于值,您当前没有进行比较。对于过滤器,它说找不到符号。您能解释一下吗?这次在@comp进行了一些更改。Collect说找不到符号。orryCollect()
小写字母非常简单,只需将这一行更改为a.getAttempts().compareTo(b.getAttempts())
像这样
//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.*;