【问题标题】:Printing the smallest people from a text file - Java从文本文件中打印最小的人 - Java
【发布时间】:2026-01-30 03:45:02
【问题描述】:

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

到目前为止,我已经使用 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

【问题讨论】:

标签: java file-io


【解决方案1】:

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

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}

【讨论】:

  • 我试过了,不行。我得到相同的输出
  • @Mudz:请查看有关排序和限制的更新答案。这可能是你的问题。
【解决方案2】:

也许你错过了像下面的例子那样赋值

List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
                               compareTo(o2.getItem().getValue())).
                               collect(Collectors.toList());

参考

Sorting a list with stream.sorted() in Java

【讨论】:

  • 感谢您的帮助,但我已经想通了