How do I sort two arrays relative to each other?

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How do I sort two arrays relative to each other? on this date .

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.


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();



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


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) { = 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 ->;

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

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