如何在Java中比较和排序两个arraylists

时间:2012-10-29 01:53:35

标签: java

我从硬盘上的两个文件获取输入:

studentNames.txt和studentScores.txt - 名称包含学生ID和姓名,而分数包含学生ID和分数。我已将数据放入两个ArrayLists中,并希望对数据进行排序,以便成绩转到匹配的ID。

例如:

+------+--------------+---------+
|  ID  |     Name     |  Grade  |
+------+--------------+---------+
| 3305 | Smith Henry  | 92.0    |
| 5555 | Eddy Olivia  | 95.5    |
| 8915 | Johnson Luke | 98.5    |
+------+--------------+---------+

数据继续填充ID / Grade - 我知道我需要使用if语句,但是我该怎么做呢?

这是我的代码:

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

public class P_Supplemental_9 {

public static void main(String[] args) throws FileNotFoundException {
   File file1 = new File("c:/temp/studentNames.txt");
   File file2 = new File("c:/temp/studentScores.txt");

   if(file1.exists()) {
   Scanner input = new Scanner(file1);

   ArrayList<Student> students = new ArrayList();

   while(input.hasNext()) {
   students.add(new Student(input.nextInt(),input.nextLine()));
   }

   input.close();

   for(int o = 0;o < students.size();o++) {
   System.out.printf("%10d %20s avg\n", students.get(o).getStuId(),     students.get(o).getStuName());

   } // end for

   }

   if(file2.exists()) {
       Scanner input = new Scanner(file2);

       ArrayList<Student> grades = new ArrayList();

       while(input.hasNext()) {
           grades.add(new Student(input.nextInt(), input.nextLine()));

       } /// end while
       input.close();

   for(int o = 0;o < grades.size();o++) {

       System.out.printf("%10d %20s avg\n", grades.get(o).getStuId(), grades.get(o).getStuName());
   } // end for

   } // end if(file2.exists)





  } // end main method
 } // end P_Supplemental_9



class Student {
    private int stuId;
    private String stuName;
    private ArrayList <Double> grades;

    Student(int idIn, String nameIn) {

        this.stuId = idIn;
        this.stuName = nameIn;
       } // end student class

    Student(int idIn, ArrayList gradesIn) {
        this.stuId = idIn;
        this.grades = gradesIn;

    }

        public int getStuId() {
            return stuId;
        }

        /**
         * @param stuId the stuId to set
         */
        public void setStuId(int stuId) {
            this.stuId = stuId;
        }

        /**
         * @return the stuName
         */
        public String getStuName() {
            return stuName;
        }

        /**
         * @param stuName the stuName to set
         */
        public void setStuName(String stuName) {
            this.stuName = stuName;
        }

        /**
         * @return the grades
         */
        public ArrayList getGrades() {
            return grades;
        }

        /**
         * @param grades the grades to set
         */
        public void setGrades(ArrayList grades) {
            this.grades = grades;
        }

} // end student class

来自Studentnames.txt的数据

3305 Smith Henry
5555 Eddy Olivia
8915 Johnson Luke

来自Studentscores.txt的数据

3305 92.0
5555 95.5
8915 98.5
3305 89.0
5555 90.5
8915 95.5
3305 78.5
5555 85.0
8915 82.0

5 个答案:

答案 0 :(得分:2)

您可以使用Collections#sort(List, Comparator)对两个列表进行排序。

假设他们是学生和他们的分数之间的一对一关系,这将允许您获得学生和分数以及列表中的每个元素。

我会想象它看起来像这样。

Collections.sort(studentNames, new Comparator<Student>() {
    public int compareTo(Student o1, Student o2) {
        return o1.getStuId() - o2.getStuId();
    }
});

这将为您提供按学生ID订购的List名学生。

然后,您将使用相同的概念来订购分数列表。一旦你有了这个,这两个列表现在应该是学生ID顺序,你应该能够循环它们。

另一个想法是将学生和分数存储在以Map为对象的学生ID中。

然后,您就可以迭代地图的键并拉出每个学生并根据这些ID进行评分

更新以满足要求

在阅读更新后的要求后,我注意到使用有序地图而不是列表会更好。

基本上,我们将每个学生姓名放入一个按个人ID键入的有序地图中。然后,我们将每个列表放在一个按照ID

键入的有序映射中的列表中
public class TestArraySort {

    public static void main(String[] args) {
        new TestArraySort();
    }

    public TestArraySort() {

        try {
            File file1 = new File("studentNames.txt");
            File file2 = new File("studentScores.txt");

            // Better to check for both files here, other wise it's just wasting time
            if (file1.exists() && file2.exists()) {
                // Create the sorted maps so that they are in scope...
                Map<Integer, String> mapStudents = new TreeMap<Integer, String>();
                Map<Integer, List<Double>> mapScores = new TreeMap<Integer, List<Double>>();

                Scanner input = null;
                try {
                    input = new Scanner(file1);
                    // Read the student information...
                    while (input.hasNext()) {
                        int id = input.nextInt();
                        String name = input.nextLine().trim();
                        mapStudents.put(id, name);
                    }
                    // Safty net
                } finally {
                    input.close();
                }

                try {
                    // Read the scores
                    input = new Scanner(file2);
                    while (input.hasNext()) {
                        int id = input.nextInt();
                        double score = input.nextDouble();

                        // If the list doesn't already exist, create it
                        List<Double> scores = mapScores.get(id);
                        if (scores == null) {
                            scores = new ArrayList<Double>(25);
                            mapScores.put(id, scores);
                        }
                        scores.add(score);
                    } /// end while
                    // Safty net
                } finally {
                    input.close();
                }

                // Dump the results
                System.out.println("+------------+----------------------+------+");
                for (Integer id : mapStudents.keySet()) {
                    // Display the student results
                    String name = mapStudents.get(id);
                    System.out.printf("| %10d | %-20s | ", id, name);
                    List<Double> scores = mapScores.get(id);
                    if (scores.size() > 0) {

                        // Sort the list
                        Collections.sort(scores);
                        // Reverse the list so that the scores are now in order from highest to lowest
                        // Sure, I could create a reverse comparator when I sort it, but
                        // I'm lazy...
                        Collections.reverse(scores);

                        // Print the first score...
                        System.out.printf("%4.1f |\n", scores.get(0));
                        // Print the remaining scores...
                        for (int index = 1; index < scores.size(); index++) {
                            System.out.printf("| %10s | %-20s | %4.1f |\n", "", "", scores.get(index));
                        }

                    } else {

                        System.out.println("00.0 |");

                    }
                    System.out.println("+------------+----------------------+------+");

                }

            } // end if(file2.exists)    }

        } catch (IOException exp) {
            exp.printStackTrace();
        }
    }
}

哪个产生

+------------+----------------------+------+
|       3305 | Smith Henry          | 92.0 |
|            |                      | 89.0 |
|            |                      | 78.5 |
+------------+----------------------+------+
|       5555 | Eddy Olivia          | 95.5 |
|            |                      | 90.5 |
|            |                      | 85.0 |
+------------+----------------------+------+
|       8915 | Johnson Luke         | 98.5 |
|            |                      | 95.5 |
|            |                      | 82.0 |
+------------+----------------------+------+

答案 1 :(得分:0)

如果您尝试比较来自不同arrayLists的两个值,假设它们是字符串值

if (array1.get(i).toString().compareTo(array2.get(j).toString()) == 0

答案 2 :(得分:0)

我认为在效率和易用性方面最好的方法是使用Map。当您读取任一文件时,将学生ID映射到与其关联的数据(名称或测试分数)。然后,遍历学生ID的集合,分别使用nameMap.get(id)scoreMap.get(id)获取名称和分数 - 其中每个id是ID集合的元素,可通过{{1获得}}

答案 3 :(得分:0)

class中实施Comparable。现在,您可以轻松致电Collections.sort(studentNames)(假设studentNamesList

答案 4 :(得分:0)

File one data
abc
abcd
bcd

file two data
abc
abcd 
bcd
cdf


final resutlt

abc
abc 
abcd
abcd
bcd
bcd
cdf



package com.ravisoft.logic;
/*
String tempDataArray[] =
    StringUtils.split(mergeStr, Utils.LINE_SEPARATOR);
java.util.Arrays.sort(tempDataArray);

String data = StringUtils.join(tempDataArray, Utils.LINE_SEPARATOR, 0);*/

import java.util.ArrayList;
import java.util.Collections;
import java.io.*;

public class ReadDemo
{
    public static void main(String args[]){
        ArrayList<String> fileData = new ArrayList<String>();
        String fileName1 = "E:\\ROUTINE_WORK\\MAY_ROUTINE_WORK\\MAY282013\\New1.TXT";
        String fileName2 = "E:\\ROUTINE_WORK\\MAY_ROUTINE_WORK\\MAY282013\\New2.TXT";
        int lines = 0;
        try 
        {
          // set up input stream1
        FileReader fr1 = new FileReader(fileName1);
          // buffer the input stream
        BufferedReader br1 = new BufferedReader(fr1);

          // set up input stream2
        FileReader fr2 = new FileReader(fileName2);
          // buffer the input stream
        BufferedReader br2 = new BufferedReader(fr2);

          // read and display1
        String buffer1 = "";



        while ((buffer1 = br1.readLine()) != null)
        {
          fileData.add(buffer1);

          System.out.println("First file: "+buffer1);  // display the line
          ++lines;
        }

      br1.close();

        String buffer2 = "";


            while ((buffer2 = br2.readLine()) != null) 
            {
                  fileData.add(buffer2);

                  System.out.println("Second file: "+buffer2);  // display the line
                  ++lines;
            }

      br2.close();
    System.out.println("Total lines before sorting: "+lines);
    lines=0;
      Collections.sort(fileData);


      System.out.println("Sorted list");
      System.out.println();
      System.out.println();
      System.out.println();
      System.out.println();
      System.out.println();

        for(String s : fileData) {
            ++lines;
          System.out.println(s);
        }
        System.out.println("Total lines after sort: "+lines);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

      }

}