简体   繁体   中英

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

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

As other said, it makes more sense if you have a separated class StudentGrade , which holds name and grade, and then you take advantage from already implemented algorithm Collections.sort , which from Java 8 accepts method reference of your class.

Here is the code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class StudentGrade {

    private String name;
    private double grade;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getGrade() {
        return grade;
    }

    public void setGrade(double grade) {
        this.grade = grade;
    }
}

public class Testcode {

    public static void main(String[] args) {

        List<StudentGrade> students = new ArrayList<>();

        students.add(new StudentGrade("Garcia", 2.5));
        students.add(new StudentGrade("Magsilang", 1.5));
        students.add(new StudentGrade("Magbag", 1.25));

        Collections.sort(students, Comparator.comparing(StudentGrade::getGrade));
        System.out.println("Grade Sorted");
        for (StudentGrade studentGrade : students) {
            System.out.println(studentGrade.getGrade() + " " + studentGrade.getName());
        }

        Collections.sort(students, Comparator.comparing(StudentGrade::getName));
        System.out.println("\nStudent Sorted");
        for (StudentGrade studentGrade : students) {
            System.out.println(studentGrade.getName() + " " + studentGrade.getGrade());
        }

    }
}

Output is:

Grade Sorted
1.25 Magbag
1.5 Magsilang
2.5 Garcia

Student Sorted
Garcia 2.5
Magbag 1.25
Magsilang 1.5

I've tried to get your 2nd output. Used Bubble sort to sort the array!

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

        //bubble sort based on ArrG array
        for (int i = 0; i < ArrG.length - 1; i++) {
            for (int j = 0; j < ArrG.length - i - 1; j++) {
                if (ArrG[j] < ArrG[j + 1]) {
                    double temp = ArrG[j];
                    ArrG[j] = ArrG[j + 1];
                    ArrG[j + 1] = temp;

                    String tempN = ArrN[j];
                    ArrN[j] = ArrN[j + 1];
                    ArrN[j + 1] = tempN;
                }
            }
        }

        // print the array
        for (int i = 0; i < ArrG.length; i++) {
            System.out.println(ArrN[i] + " " + ArrG[i]);
        }
    }
}

Output:

Garcia 2.5
Magbag 1.5
Magsilang 1.25

This is a basic approach! You can also use a Class or built-in Array() methods!

To get a sorted copy of two arrays with respect to each other you can first link in pairs the elements of these arrays, and then sort these pairs - you get a sorted list. As a container for each pair you can use Map.Entry , or an array, or some class . For example:

String[] arrN = {"Garcia", "Magsilang", "Magbag"};
double[] arrG = {2.5, 1.25, 1.5};
List<Map.Entry<String, Double>> list = IntStream
        // assuming the two arrays are the same length,
        // iterate over the indices of the first array
        .range(0, arrN.length)
        // link a pair of two elements
        .mapToObj(i -> Map.entry(arrN[i], arrG[i]))
        // collect a list of map entries
        .collect(Collectors.toList());
// sort by name
list.sort(Map.Entry.comparingByKey());
list.forEach(System.out::println);
//Garcia=2.5
//Magbag=1.5
//Magsilang=1.25
// sort by grades
list.sort(Map.Entry.comparingByValue());
list.forEach(System.out::println);
//Magsilang=1.25
//Magbag=1.5
//Garcia=2.5

See also: How do I relate one array input to another?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM