Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

Ordenando caso um dos atributos de ordenação seja igual

Olá,

Estou tentando resolver um problema onde tenho uma lista de estudantes e devo ordená-los de acordo com o CGPA (como se fosse a média) de cada um em ordem decrescente, caso elas sejam iguais, devo ordená-los pelo seu nome e por fim caso os nomes sejam iguais, devo ordená-los pelo seu id, ja tentei de diversas formas fazendo um if na classe de teste dizendo que se tal condição for igual, utilizar então outro método de ordenação, como ordem natural, deixei que fosse ordenada pelo CGPA, já que é o primeiro quesito de ordenação e aí fazendo a ordenação pelo Collections.sort(); e tentando implementar as condicionais na classe teste, segue o código, se alguém pudesse me ajudar agradeceria muito pois estou o dia inteiro tentando arrumar uma solução e não estou conseguindo, obrigado!

public class Student implements Comparable<Student> {

    private int id;
    private String fname;
    private double cgpa;

    public Student(int id, String fname, double cgpa) {
        this.id = id;
        this.fname = fname;
        this.cgpa = cgpa;
    }

    public int getId() {
        return id;
    }

    public String getFname() {
        return fname;
    }

    public double getCgpa() {
        return cgpa;
    }

    //neste caso eu inverti a ordem dos resultados pois solicita que seja feito pelo CGPA em ordem descrescente
    @Override
    public int compareTo(Student anotherStudent) {

        if(this.getCgpa() < anotherStudent.getCgpa()) {
            return 1;
        }
        if(this.getCgpa() > anotherStudent.getCgpa()) {
            return -1;
        }
        return 0;
    }
}

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

import com.hackerrank.model.Student;

public class TesteComparacao {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int testCases = Integer.parseInt(in.nextLine());

        List<Student> studentList = new ArrayList<Student>();
        while (testCases > 0) {
            int id = in.nextInt();
            String fname = in.next();
            double cgpa = in.nextDouble();

            Student st = new Student(id, fname, cgpa);
            studentList.add(st);

            testCases--;
        }

        for(int i = 0; i < studentList.size(); i++) {
            Collections.sort(studentList);
            if(studentList.get(i).getCgpa() == studentList.get(i).getCgpa()) {
                studentList.sort(new Comparator<Student>() {

                    @Override
                    public int compare(Student student1, Student student2) {
                        return student1.getFname().compareTo(student2.getFname());
                    }
                });
            } else if(studentList.get(i).getFname() == studentList.get(i).getFname()) {
                studentList.sort(new StudentIdComparator());
            }
        }

        for (Student st : studentList) {
            System.out.println(st.getFname());
        }
    }
}

class StudentIdComparator implements Comparator<Student> {

    @Override
    public int compare(Student student1, Student student2) {

        if (student1.getId() < student2.getId()) {
            return -1;
        }
        if (student1.getId() > student2.getId()) {
            return 1;
        }
        return 0;
    }
}
1 resposta
solução!

Consegui resolver!

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software