繁体   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