[英]Refactor loops and conditions with Java 8 streams
我有一個類似的代碼片段:
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>>
,有人可以建議如何實現此方法嗎? 謝謝!
您需要在兩者之間使用flatMap
將Ticket
對象的列表轉換為流,以便可以過濾Ticket
。 您可以引用以下代碼(帶有內聯注釋)以使用流獲得結果:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.