Filter using stream with Class Lists that contain lists of other classes

Asked

Viewed 899 times

0

I have the following class structure

public class Linha implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private String prefixo;
    private String nome;
    private LocalDate dataInicio;
    private LocalDate dataLimite;
    private Status status;
    private List<Itinerario>  itinerarios;
    //Demais get set e metodos
}   
public class Itinerario implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private Sentido sentido;
    private List<PontoDoItinerario> pontosDoItinerario;
    private List<Horario> hoariosDoItinerario;
    private Linha linha;
    //Demais get set e metodos
}   
public class PontoDoItinerario implements Serializable,Comparable<PontoDoItinerario> {
    private static final long serialVersionUID = 1L;
    private Long id;
    private Integer sequencia;
    private PontoDeParada pontoDeParada;
    private Itinerario itinerario;
    private BigDecimal km;
    private LocalTime tempoEstimado;
    //Demais get set e metodos
}   
public class PontoDeParada implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private String prefixo;
    private String nome;
    private double latitude;
    private double longitude;
    private String referencia;
    //Demais get set e metodos
}       

I have a list of Lines:

  • Containing a list of Itineraries
  • That contains a list of Pontodoitinerario
  • which contains a stop per item

I need to make a filter by the Stop id.

How can I do this using the java 8 stream.filter?

1 answer

1

An example of Stream:

List<PontoDeParada> pontos = new ArrayList<>();

If you want to receive the result of the filtering in a Stream do so:

Stream<PontoDeParada> stream = pontos.stream().filter((p) ->  
{ /*aqui você faz a implementação da filtragem, que devolve um valor booleano.  
Por exemplo: return p.id > 10;  */ });

The problem is that the object Stream may be used only once. If you want to keep in one ArrayList of PontoDeParada can do so:

ArrayList<PontoDeParada> maisQ10 = new ArrayList<>();  
pontos.stream().filter( p -> p.id > 10).forEach(maisQ10.add(p));
  • Actually I need the whole tree but the filter is on the last level. .

Browser other questions tagged

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