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

时间:2017-11-24 11:11:44

标签: java file-io

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

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

2 个答案:

答案 0 :(得分: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}

答案 1 :(得分:0)

也许您错过了分配价值,例如以下示例

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