Dmitry  Adonin
Dmitry Adonin

Reputation: 1204

Refactor loops and conditions with Java 8 streams

I have a code snippet like:

List<Ticket> lowestPriceTickets(List<Info> infos, Ticket lowestPriceTicket) {
    List<Ticket> allLowestPriceTickets = new ArrayList<>();

    for (Info info : infos)
    {
        if (info.getTicketTypeList() != null)
        {
            for (Ticket ticket : info.getTicketTypeList())
            {
                if (lowestPriceTicket.getCode().order() == ticket.getCode().order())
                {
                    allLowestPriceTickets.add(ticket);
                }
            }
        }
    }
    return allLowestPriceTickets;
}

I'm trying to refactor it using Java 8 streams but stucked after

infos.stream()
                .filter(info -> info.getTicketTypeList() != null)
                .map(Info::getTicketTypeList)

because I would like to filter each Ticket but see Stream<List<Ticket>>, could someone suggest please how this method should be accomplished? Thank you!

Upvotes: 2

Views: 523

Answers (1)

Vasu
Vasu

Reputation: 22422

You need to use flatMap in between to convert the list of Ticket objects into stream so that you can filter the Tickets. You can refer the below code (with inline comments) to achieve the result using streams:

List<Ticket> ticketsList = infos.stream()
   .filter(info -> info.getTicketTypeList() != null)//filter the list if null
   .map(info -> info.getTicketTypeList())//get the tickettype list
   .flatMap(ticketsList -> ticketsList.stream())//convert to stream of tickets
   .filter(lowestPriceTicket -> 
       lowestPriceTicket.getCode().order() == 
          ticket.getCode().order())//check if it matches with the given ticket
   .collect(Collectors.toList());//now collect it to a List<Ticket>

Upvotes: 6

Related Questions