How do I sort two arrays relative to each other?

I am trying to make a Student Grade Program where there are 2 arrays: String[] Student and double[] Grade. I cloned them to have a sorted array and an unsorted one.

Arrays:

public class Testcode {
    public static void main(String[] args) {
        String ArrN[] = {"Garcia", "Magsilang", "Magbag"};
        double ArrG[] = {2.5, 1.25, 1.5};

        String ArrN2[] = ArrN.clone();
        double ArrG2[] = ArrG.clone();

        Arrays.sort(ArrN2);
        Arrays.sort(ArrG2);

        System.out.println(Arrays.toString(ArrN1));
        System.out.println(Arrays.toString(ArrN2));
        System.out.println(Arrays.toString(ArrG2));
        System.out.println(Arrays.toString(ArrG2));
    }
}

Now, how do I make an output that looks like the one below (Grade Sorted)

- 1.25               Magsilang
- 1.5                Magbag
- 2.5                Garcia

or (Student Sorted)

- Garcia             2.5
- Magbag             1.5
- Magsilang          1.25

Answer

Since you’re not dealing individually with only names and grades. I would suggest creating a StudentGrade class for your problem like this:

private static class StudentGrade {
    String name;
    double grade;

    public StudentGrade(String n, double g) {
        this.name = n;
        this.grade = g;
    }
}

You can create an array of StudentGrade[] and sort it with whatever field which fits your use case. I sorted it with name and grade and I was able to see expected output;

StudentGrade[] studentGrades = new StudentGrade[] {
        new StudentGrade("Garcia", 2.5),
        new StudentGrade("Magsilang", 1.25),
        new StudentGrade("Magbag", 1.5)
};

// Sort By Name
System.out.println("(Student Sorted):");
Arrays.sort(studentGrades, Comparator.comparing(o -> o.name));
printStudentGrades(studentGrades);

// Sort by Grade
System.out.println("(Grade Sorted):");
Arrays.sort(studentGrades, Comparator.comparing(o -> o.grade));
printStudentGrades(studentGrades);

This prints this output:

(Student Sorted):
Garcia 2.5
Magbag 1.5
Magsilang 1.25
(Grade Sorted):
Magsilang 1.25
Magbag 1.5
Garcia 2.5