簡體   English   中英

檢查Java列表並根據某些條件創建一個新列表

[英]Check a Java list and create a new one according to some criteria

我有一個帶有“ Booking”對象的列表 “預訂”具有以下屬性:-long roomId。 日期fecha。 長訂單。 雙重價格。

在某個時刻,此列表可能是:

1-22/07/2016-15
1-2016年7月23日-15
1-24/07/2016-15
4-01/08/2016-25
4-02/08/2016-25
4-03/08/2016-25
4-04/08/2016-25

這意味着在7月22日至24日之間有1個房間的預訂,總價值45。在8月1日至4日之間有4個房間的預訂,價值100。

我想制作一個“ OrderDetail”對象的新列表。 “ OrderDetail”對象將具有以下屬性:
-roomId,InitialDate,FinalDate,價格

因此,使用我的列表,它將創建兩個OrderDetail對象,並將其添加到OrderDetail列表中。 這些對象將是:

  • roomId = 1,InitialDate = 22/07/2016,FinalDate = 24/07/206,價格= 45
  • roomId = 4,InitialDate = 01/08/2016,FinalDate = 04/08/2016,價格= 100。

有人可以幫我嗎? 我認為這不是一個困難的代碼,但是我通常不編程,因此在使其工作上遇到了一些問題。

這是我糟糕的代碼:

 L1 = (this is a database query)
L2 = (this is the same query) (so I have two identical lists)

List<OrderDetail> L3 = new ArrayList<OrderDetail>();
Long roomId = null;
Date InititalDate;
Date FinalDate;
double price = 0;

for (int i = 0; i < L1.size(); i++) {

    InititalDate = null;
    Booking current = L1.get(i);

    roomId = current.getRoomId();
    InititalDate = current.getFecha();

    Iterator<Booking> it = L2.iterator();
    while (it.hasNext()) {
        Booking current2 = it.next();
        if (current2.getRoomId.equals(roomId)) {
            precio = precio + current2.getPrecio();
            FinalDate = current2.getFecha();
            i++;
        }

    }

    OrderDetail = new OrderDetail(roomId, InitialDate, FinalDate, precio);
    L3.add(OrderDetail);

}

return L3;

}

我正在學習Java8 ,只是嘗試使用streams來實現您所要求的

    Booking b1 = new Booking(1L, LocalDate.of(2016, 7, 22), 15d);
    Booking b2 = new Booking(1L, LocalDate.of(2016, 7, 23), 15d);
    Booking b3 = new Booking(1L, LocalDate.of(2016, 7, 24), 15d);
    Booking b4 = new Booking(4L, LocalDate.of(2016, 8, 1), 25d);
    Booking b5 = new Booking(4L, LocalDate.of(2016, 8, 2), 25d);
    Booking b6 = new Booking(4L, LocalDate.of(2016, 8, 3), 25d);
    Booking b7 = new Booking(4L, LocalDate.of(2016, 8, 4), 25d);

    List<Booking> bookings = Arrays.asList(b1, b2, b3, b4, b5, b6, b7);

    List<OrderDetail> orderDetails = bookings
            .stream().collect(Collectors.groupingBy(Booking::getRoomId)).values().stream().map(i -> new OrderDetail(i.get(0).getRoomId(),
                    i.get(0).getBookedDate(), i.get(i.size() - 1).getBookedDate(), i.stream().collect(Collectors.summingDouble(Booking::getPrice))))
            .collect(Collectors.toList());

    System.out.println(orderDetails);

輸出

[OrderDetail [roomId=1, startDate=2016-07-22, endDate=2016-07-24, totalPrice=45.0], OrderDetail [roomId=4, startDate=2016-08-01, endDate=2016-08-04, totalPrice=100.0]]

請注意:我相信可能會有更好的方法來實現這一點,請添加您的答案,以便從中學習

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM