使用Java 8流重构循环和条件

时间:2017-03-18 18:17:10

标签: java java-8 java-stream

我有一个代码片段,如:

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;
}

我正在尝试使用Java 8流重构它,但在

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

因为我想过滤每个Ticket,但请看Stream<List<Ticket>>, 有人可以建议请问这种方法应该如何完成? 谢谢!

1 个答案:

答案 0 :(得分:5)

您需要在两者之间使用flatMapTicket对象列表转换为流,以便您可以过滤故障单。您可以参考下面的代码(带内联注释)来使用流来实现结果:

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>