比较文本文件中的数组 - Java

时间:2017-11-23 22:43:57

标签: java

import java.util.*;
import java.io.*;

public class Animal1 {
    public static void main( String [] args ) throws IOException {
        ArrayList<Animal> animalFile = new ArrayList<>();

        try {
            BufferedReader br = new BufferedReader(new FileReader("animal.txt"));
            String fileRead = br.readLine();            
            while (fileRead != null) {                
                String[] tokenSize = fileRead.split(":");
                String animalName = tokenSize[0];
                int maxLength = Integer.parseInt(tokenSize[1]);
                Animal animalObj = new Animal(animalName, maxLength);
                animalFile.add(animalObj);
                fileRead = br.readLine();
            }
            br.close(); 
        }
        catch (FileNotFoundException e){
            System.out.println("file not found");
        }
        System.out.println("The three largest animals are: ");
    }    
}

这是我的代码到目前为止,它从我的动物文件中提取数据并输出我为文件中的每个对象创建的数组。我如何比较Java中的数组,以便打印出三个最大的动物,按照最大的动物排序?我想在换行符上打印动物名称以及最大长度。

3 个答案:

答案 0 :(得分:0)

要打印3种最大的动物,你可以这样做:

  • sort maxLength列表以相反的顺序获得最大的第一个
  • 然后keep 3个第一个
  • print他们
animalFile.stream()
          .sorted(Comparator.comparingInt(Animal::getMaxLength).reversed())
          .limit(3)
          .forEach(a -> System.out.println(a.animalName + ", length " + a.maxLength));

getMaxLength()是getter方法

第一种方法不会对列表进行排序,这一个是:

Collections.sort(animalFile,Comparator.comparingInt(Animal::getMaxLength).reversed()); 
animalFile.stream().limit(3).forEach(System.out::println);  //Will use toString() you write

答案 1 :(得分:0)

类似的东西:

animalFile.stream()
          .sorted(Comparator.comparingInt(Animal::getMaxLength).reversed())
          .limit(3)
          .forEach(e -> { /* do logic */ });

答案 2 :(得分:0)

你可以这样做:

Collections.sort(animalFile, Collections.reverseOrder(Comparator.comparingInt(a-> a.getMaximumLength())));

System.out.print("The 3 largest animals are: ");

animalFile.subList(0, 3).stream().forEach(n -> System.out.print(n.animalName + " "));