How to add element inside an arrayList that is inside another Arraylist that in turn is inside a Hashmap?

Asked

Viewed 1,430 times

2

The question is: I have the Classes Student, Discipline, Grade, Class.

I need to add a double value in an Arraylist that is in an object of the Discipline class, but the Discipline class is inside in an Arraylist and this Arraylist is inside a Hashmap:

this is the method I’m trying to add to note:

public void addNota(String numeroMatricula, String disciplina,double nota){
    Iterator i = formaTurma.keySet().iterator();
    while(i.hasNext()){
        Aluno aluno = (Aluno)i.next();
        if(aluno.getNumeroMatricula().equals(numeroMatricula)){
            ArrayList<Disciplina> disc = new ArrayList<Disciplina>();
            disc.addAll(formaTurma.get(aluno));
            for(int j = 0; j < disc.size(); j++){
                if(disc.get(j).getNome().equals(disciplina)){
                    O QUE FAÇO AQUI??
                }
            }
        }
    }
}

How do I manipulate this method? I just need to add the note inside the arrayList, but I don’t know how to do it.

1 answer

2

  • You didn’t say what exactly the field is formaTurma. I suppose it’s a Map<Aluno, List<Disciplina>>, correct? Ideally I shouldn’t have to assume this, since you should have informed in your question.
  • Ideally there should be a Map<String, Aluno> somewhere so you are not required to go through the formaTurma looking for the Aluno that matters, because the idea of Map is exactly give you the value when you give the key. If you do not know the key and are obliged to look for it within the keySet() of Map, then you’re doing something wrong.
  • Ideally, a student’s subjects should be within the class itself Aluno, and not in a Map external. So I could use aluno.getDisciplinas() to find a student’s subjects instead of using formaTurma.get(aluno). This probably demonstrates some serious problem in object orientation. Moreover, these subjects per student should ideally be a Map<String, Disciplina> so that I did not need to seek the correct discipline within a list.
  • Because instead of iterating the list of disciplines of Aluno, are you creating a new list and iterating this new list? Wouldn’t it be easier and simpler to iterate the original list?
  • Why you iterate the list of disciplines using the get(int) instead of using the Enhanced-for or the Iterator which would be the simplest and most natural way?
  • You said the grade list is inside the class Disciplina, but you haven’t shown me how to get it, and with that I can’t answer your question without having to make some kind of assumption that I shouldn’t be making. I’ll assume there’s in the class Disciplina a method getNotas() that returns a List<Double>, but if I’m wrong, it’s because you haven’t given enough information so your question can be answered.

Anyway, if all this were observed, I would just need to do this:

private Map<String, Aluno> alunos;

public void addNota(String numeroMatricula, String disciplina, double nota) {
    Aluno aluno = alunos.get(numeroMatricula);
    if (aluno == null) throw new IllegalArgumentException("O aluno com número de matrícula " + numeroMatricula + " não existe.");
    Disciplina d = aluno.getDisciplinas().get(disciplina);
    if (disciplina == null) throw new IllegalArgumentException("O aluno com número de matrícula " + numeroMatricula + " não possui nenhuma disciplina " + disciplina + ".");
    d.getNotas().add(nota);
}

Or if you have how to ensure that the parameters numeroMatricula and disciplina will always be valid, you can further simplify:

private Map<String, Aluno> alunos;

public void addNota(String numeroMatricula, String disciplina, double nota) {
    alunos.get(numeroMatricula).getDisciplinas().get(disciplina).getNotas().add(nota);
}

However if you cannot change the class structure Aluno nor can it change the shape of the Map formaTurma for Map<Aluno, Map<String, Disciplina>> or to Map<String, Map<String, Disciplina>> and can’t even add a Map<String, Aluno> somewhere, so I’d do the following:

private Map<Aluno, List<Disciplina>> formaTurma;

private Aluno procurarAlunoPorNumeroDeMatricula(String numeroMatricula) {
    for (Aluno aluno : formaTurma.keySet()) {
        if (aluno.getNumeroMatricula().equals(numeroMatricula)) return aluno;
    }
    return null;
}

public void addNota(String numeroMatricula, String disciplina, double nota) {
    Aluno aluno = procurarAlunoPorNumeroDeMatricula(numeroMatricula);
    if (aluno == null) throw new IllegalArgumentException("O aluno com número de matrícula " + numeroMatricula + " não existe.");
    List<Disciplina> disciplinas = formaTurma.get(aluno);
    for (Disciplina d : disciplinas) {
        if (d.getNome().equals(disciplina)) {
            d.getNotas().add(nota);
            return;
        }
    }
    throw new IllegalArgumentException("O aluno com número de matrícula " + numeroMatricula + " não possui nenhuma disciplina " + disciplina + ".");
}

Or if you’re using java 8:

private Map<Aluno, List<Disciplina>> formaTurma;

public void addNota(String numeroMatricula, String disciplina, double nota) {
    formaTurma.entrySet().stream() // Itera todos os Map.Entry<Aluno, List<Disciplina>>.
            .filter(e -> e.getKey().getNumeroMatricula().equals(numeroMatricula)) // E escolhe só os que tiverem o número de matrícula correto (mesmo que seja só uma).
            .findFirst() // Obtém um Optional<Map.Entry<Aluno, List<Disciplina>>> que contém o primeiro (e supostamente único) entry, se ele de fato existir. 
            .orElseThrow(() -> new IllegalArgumentException("O aluno com número de matrícula " + numeroMatricula + " não existe.")) // Se o entry não existir lança exceção.
            .getValue().stream() // E itera o List<Disciplina>.
            .filter(d -> d.getNome().equals(disciplina)) // E escolhe só as que tiverem o nome correto (mesmo que seja só uma).
            .findFirst() // Obtém um Optional<Disciplina> que contém a primeira (e supostamente única) disciplina, se ela de fato existir.
            .orElseThrow(() -> new IllegalArgumentException("O aluno com número de matrícula " + numeroMatricula + " não possui nenhuma disciplina " + disciplina + ".")) // Se a disciplina não existir lança exceção.
            .getNotas() // Obtém o List<Double>.
            .add(nota); // E adiciona a nota lá.
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.