How to add element inside an arrayList that is inside another ArrayList that in turn is inside a HashMap?

2

The question is: I have the Classes Student, Discipline, Note, 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 an ArrayList and this ArrayList is inside a HashMap:

This is the method I'm trying to add to the 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 handle this method? I just need to add the note inside the arrayList, but I do not know how to do that.

    
asked by anonymous 19.01.2015 / 21:45

1 answer

2
  • You did not say what exactly is the formaTurma field. I suppose it's a Map<Aluno, List<Disciplina>> , right? Ideally I should not have to assume this, since you should have informed in your question.
  • Ideally there should be Map<String, Aluno> somewhere so you do not have to go through formaTurma by looking for Aluno that matters, since the idea of Map is exactly give you the value when you give% key. If you do not know the key and are forced to look for it within keySet() of Map , then you are doing something wrong. Ideally, a student's subjects should be within the Aluno class itself, not an external Map . So I could use aluno.getDisciplinas() to find the disciplines of a student instead of using formaTurma.get(aluno) . This probably demonstrates some serious object-orientation problem. In addition, these student disciplines should ideally be Map<String, Disciplina> so that I do not have to search for the correct discipline within a list.
  • Why instead of iterating the Aluno list of subjects, are you creating a new list and iterating this new list? Would not it be a lot easier and simpler to iterate through the original list?
  • Why do you iterate through the list of disciplines using get(int) instead of using enhanced-for or Iterator that would be the simplest and most natural way to iterate?
  • You said that the list of grades is within the Disciplina class, but you have not demonstrated how to get it, so you can not answer your question without having to make some sort of assumption that I should not be doing. I'll assume there is a Disciplina class in% class that returns a getNotas() , but if I'm wrong, it's because you did not give enough information so your question could be answered.

Anyway, if all of this were noted, 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 a way to ensure that the parameters List<Double> and numeroMatricula will always be valid, you can simplify further:

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 can not change the structure of the disciplina class and can not change the format from Aluno Map to formaTurma or Map<Aluno, Map<String, Disciplina>> and can not add Map<String, Map<String, Disciplina>> somewhere, then I would 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á.
}
    
19.01.2015 / 23:38