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

如何在Java中比较和排序两个ArrayList,java,Java,我从硬盘上的两个文件获取输入: studentNames.txt和studentScores.txt-名称包含学生ID和姓名,而分数包含学生ID和分数。我已经将数据放入两个ArrayList中,并希望对数据进行排序,以便将分数转到匹配的ID 例如: +------+--------------+---------+ | ID | Name | Grade | +------+--------------+---------+ | 3305 | Smith Henry |

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

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

例如:

+------+--------------+---------+
|  ID  |     Name     |  Grade  |
+------+--------------+---------+
| 3305 | Smith Henry  | 92.0    |
| 5555 | Eddy Olivia  | 95.5    |
| 8915 | Johnson Luke | 98.5    |
+------+--------------+---------+
数据继续只填充ID/等级-我知道我需要使用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
以下是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

如果您试图比较来自不同ArrayList的两个值,则假定它们是字符串值

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

可用于对两个列表进行排序

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

我会想象它看起来像这样

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

+------------+----------------------+------+
|       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 |
+------------+----------------------+------+

我认为最好的方法,无论是从效率还是写作的简易性来看,都是使用一个新的方法。在读取任一文件时,将学生ID映射到与其关联的数据(姓名或考试分数)。然后,遍历学生ID集合,分别使用
nameMap.get(ID)
scoreMap.get(ID)
获取姓名和分数,其中每个
ID
都是ID集合的一个元素,可以通过
nameMap.keySet()在
类中实现。现在,您可以轻松调用
Collections.sort(studentNames)
(假设
studentNames
是一个)

文件一个数据
abc
abcd
卡介苗
归档两个数据
abc
abcd
卡介苗
cdf
最终结果
abc
abc
abcd
abcd
卡介苗
卡介苗
cdf
包com.ravisoft.logic;
/*
字符串tempDataArray[]=
StringUtils.split(mergeStr、Utils.LINE\u分隔符);
java.util.Arrays.sort(tempDataArray);
String data=StringUtils.join(tempDataArray,Utils.LINE_分隔符,0)*/
导入java.util.ArrayList;
导入java.util.Collections;
导入java.io.*;
公共类ReadDemo
{
公共静态void main(字符串参数[]){
ArrayList fileData=新的ArrayList();
String fileName1=“E:\\ROUTINE\u WORK\\MAY\u ROUTINE\u WORK\\MAY282013\\New1.TXT”;
String fileName2=“E:\\ROUTINE\u WORK\\MAY\u ROUTINE\u WORK\\MAY282013\\New2.TXT”;
int行=0;
尝试
{
//设置输入流1
FileReader fr1=新的FileReader(fileName1);
//缓冲输入流
BufferedReader br1=新的BufferedReader(fr1);
//设置输入流2
FileReader fr2=新的FileReader(fileName2);
//缓冲输入流
BufferedReader br2=新的BufferedReader(fr2);
//读取并显示1
字符串缓冲区1=“”;
而((buffer1=br1.readLine())!=null)
{
fileData.add(buffer1);
System.out.println(“第一个文件:+buffer1);//显示行
++线条;
}
br1.close();
字符串缓冲区2=“”;
而((buffer2=br2.readLine())!=null)
{
fileData.add(buffer2);
System.out.println(“第二个文件:+buffer2);//显示行
++线条;
}
br2.close();
System.out.println(“排序前的总行数:+行”);
直线=0;
Collections.sort(fileData);
System.out.println(“排序列表”);
System.out.println();
System.out.println();
System.out.println();
System.out.println();
System.out.println();
for(字符串s:fileData){
++线条;
系统输出打印项次;
}
System.out.println(“排序后的总行数:“+行”);
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}

你应该说得更清楚些。为什么此arraylist包含的“object”类型?@hqt是否希望我发布我的代码?@user1717964是的,特别是数据的结构具有两个输入文件的实际示例也会有所帮助。通常,有一种更好的解决问题的方法是从另一个角度从头开始。@hqt包含整个文件,包括两个数据文件。我有三个单独的值:int、double和string。int是学生id,double是学生的成绩,字符串是名字。。。我需要将多个成绩与多个ID进行匹配。我们还没有使用Map-不知道怎么做。我希望你没有:P-如果可以,用代码的相关部分(学生和分数的加载)和每个文件中的一些样本数据更新你的问题。我编辑了它以显示我的主要方法。我下面有一个班级,但我想你会得到答案。你有重复的小组(也就是说,每个学生有一个或多个分数)。你想要平均的还是排序的…?是的…所以,班上有三个学生,每个人都有多个分数。我希望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 |
+------------+----------------------+------+
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();
        }

      }

}