Dorian Gray
Dorian Gray

Reputation: 27

How does map() in Streams works and how to work with it when the argument is a Collection

I am working with Streams in Java 8. I need to implement a method in the Colegio class where it returns each note (Inscripcion.getNota()) from the list "inscriptionList" in the Curso class. Use filter() to know the notes of a Curso passed its "Name" (nombreCurso) by parameter. The method must be implemented using Streams. I don't understand how the map() method works using a List as an argument. Its possible something like this? (void notasDelCurso(nombreCurso))

In Colegio class:

public class Colegio {
    private List<Curso> cursos;

    //Constructor and getter omitted

public void notasDelCurso(String nombreCurso){
    cursos.stream()
          .filter(s -> s.getNombreCurso().equals(nombreCurso))
          .map(s -> s.getInscripcionList().stream()
                                          .map(j -> j.getNota()))
          .forEach(s -> System.out.println(s));
}

Curso:

public class Curso {
    private String nombreCurso;
    private Integer cupo;
    private double notaAprobacion;
    private List<Inscripcion> inscripcionList;

   //Constructor and getter omitted

Inscripcion:

public class Inscripcion {
    private Alumno alumno;
    private Curso curso;
    private long nota;

    //Constructor and getter omitted

The output: java.util.stream.ReferencePipeline$3@5fd0d5ae

Upvotes: 2

Views: 66

Answers (1)

Naman
Naman

Reputation: 32046

I don't understand how the map() method works using a List as an argument

The map method transforms the current entity type to another type based on the Function you've provided.

The output: java.util.stream.ReferencePipeline$3@5fd0d5ae

The output in your case for the same reason is printing the Stream to which you have mapped your initial entities.


When dealing with List or any other collection of entities, you want to flatten the collection and while transforming and for that you could use flatMap operation from Stream. In the code you've shared, you can use it in the form of:

.flatMap(s -> s.getInscripcionList().stream()
                              .map(j -> j.getNota()))

Upvotes: 2

Related Questions