gpt4 book ai didi

java - 从文本文件打印最小的人 - Java

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:48:41 24 4
gpt4 key购买 nike

我想按长度打印出三个最小的人,从最小的开始排序,它需要在换行符上打印出每个人的名字以及文本文件中以厘米为单位的最大长度。

到目前为止,我已经使用 Collections.sort 创建了一个比较器,用于整理我在文件中创建的数组,并对它们进行排序。

比较器:

Collections.sort(peopleFile,Comparator.comparingInt(People::getMaximumLength).reversed());

数组:

List<People> peopleFile = new ArrayList<>();
String[] tokenSize = fileRead.split(":");
String peopleName = tokenSize[0];
int maximumLength = Integer.parseInt(tokenSize[1]);

打印:

System.out.println("The three smallest people are: ");
peopleFile.stream().limit(3).forEach(System.out::println);

输出:

The three smallest people are:
David Lee, Length = 150 centimetres
Amber Jones, Length = 142 centimetres
Mandy Stones, Length = 152 centimetres

问题是它没有输出最大的人,它只是打印出文本文件中的顺序。

我的输出应该是这样的:

The three smallest people are:
Amber Jones, Length = 142 centimetres
Samantha Lee, Length = 144 centimetres
Andre Bishop, Length = 145 centimetres

最佳答案

如果你想输出三个最小的人,你应该使用:

Collections.sort(peopleFile,Comparator.comparingInt(People::getMaximumLength));

代替:

Collections.sort(peopleFile,Comparator.comparingInt(People::getMaximumLength).reversed());

而且你必须排序然后限制。不要试图先限制再排序。

有关工作示例,请参见下面的示例:

public static void main(String[] args) {

class People {
String peopleName;
int maximumLength;

public People(String peopleName, int maximumLength) {
this.peopleName = peopleName;
this.maximumLength = maximumLength;
}

public int getMaximumLength() {
return maximumLength;
}

@Override
public String toString() {
return "{" +
"peopleName='" + peopleName + '\'' +
", maximumLength=" + maximumLength +
'}';
}
}

List<People> people = Arrays.asList(new People("John", 175), new People("Jane", 168),
new People("James", 189), new People("Mary", 167),
new People("tim", 162));
people.stream().sorted(Comparator.comparingInt(People::getMaximumLength)).limit(3).forEach(System.out::println);
System.out.println();
people.stream().sorted(Comparator.comparingInt(People::getMaximumLength).reversed()).limit(3).forEach(System.out::println);
}

这将首先打印出 3 个最矮的,然后打印出 3 个最高的:

{peopleName='tim', maximumLength=162}
{peopleName='Mary', maximumLength=167}
{peopleName='Jane', maximumLength=168}

{peopleName='James', maximumLength=189}
{peopleName='John', maximumLength=175}
{peopleName='Jane', maximumLength=168}

关于java - 从文本文件打印最小的人 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47472054/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com