Given the description of the problem, unless I have not understood something, there is nothing better that can be done.
If you have any unexplained details, you may eventually find an optimization but there is no miracle. Only if there is a criterion that makes it easier to take some shortcut.
One thing you can do is have a single list that has all the data, but it will hardly be a good idea, easy on one side, difficult on another.
Even with this solution, you may have a for
. But so what? Why is this a better code? Just because you have fewer links? This does not mean that the code is better written. In any case, it would probably have to have three if
to identify the breach of the grouping, so maybe it would be even worse. And another, changes the data structure because of the algorithm. So yes, it would be a beautiful practice in most situations.
And understand that good or bad practice refers to common cases in a large number of cases. They can not be followed in all cases.
What you can do is separate this into methods for each interaction, so you would only have a for
in each method. But it would still have 4 for
. Does this make the code better? In some chaos, yes. But not necessarily, it depends on the goal. Separating too much can bring as much trouble as heaping too much. It would be something like this (roughly):
void getGeneros(ArrayList biblioteca) {
for (Genero genero : biblioteca.getLista()) {
getArtistas(genero);
}
}
void getArtistas(ArrayList genero) {
for (Artista artistas : genero.getLista()) {
getAlbuns(artistas);
}
}
void getAlbuns(ArrayList artista) {
for (Album album : artista.getLista()) {
getMusicas(album);
}
}
void getMusicas(ArrayList album) {
for (Musica musica : album.getLista()) {
GravaMusica(musica);
}
}
It's just an example. I have doubts if it is better, I think it got worse, it got repetitive depending on what each GetLista()
does. Anyway I think the names of variables and types are better defined there. Since you like good practice, try to name everything well in your program, this helps a lot. It could be a better example but I do not know the whole context.
If the problem is performance it may be possible to break the operation and put the processors to work in parallel, but then the problem would already be different from what was described. And it may not even be worth the effort.