I have a many to many table of orders. For every order id there can be a lot of product ids. When I fetch the data from db I'm trying to get all the products for every order respectively in a view object. The idea was to check if the order id of the last element in LinkedList (the list I'm trying to return with the method) is the same as the order id of the next element that I am trying to write into the list. If the order is the same I add another product to that order, if it isn't I make a new order with its product.
public List<OrderVO> getOrders(int id) {
List<Orders> orders = orderRepository.findByUserId(id);
List<OrderProduct> orderProduct = new ArrayList<>();
for (Orders o : orders) orderProduct = orderProductRepository.findByOrderId(o.getId());
LinkedList<OrderVO> orderz = new LinkedList<>();
for (OrderProduct op : orderProduct) {
OrderVO order = new OrderVO(Long.valueOf(op.getOrders().getId()));
Optional<Product> pResponse = productRepository.findById(op.getProduct().getId());
Product p = pResponse.get();
ProductVO pVO = new ProductVO(p.getId(), p.getName(), op.getAmountOfOrderedProduct());
if (orderz.peekLast().getId() == order.getId()) {
OrderVO o = orderz.getLast();
o.getOrderProducts().add(pVO);
orderz.addLast(o);
} else {
order.getOrderProducts().add(pVO);
orderz.addLast(order);
}
}
return orderz;
}
The problem is that orderz.peekLast().getId() at first iteration always throws a Null Pointer Exception. So i tried to check if its null gracefully with a optional like so:
Optional<LinkedList<OrderVO>> orderz = Optional.ofNullable(new LinkedList<>());
.
.
.
if (orderz.ifPresent(orderVOS -> orderz.get().peekLast().getId()) == order.getId()) {
OrderVO o = orderz.get().getLast();
o.getOrderProducts().add(pVO);
orderz.get().addLast(o);
} else {
order.getOrderProducts().add(pVO);
orderz.get().addLast(order);
}
Though it seems that the orderz.ifPresent(orderVOS -> orderz.get().peekLast().getId()) defualt value is void so i can't compare it with an int. Ironically for this one, I try to keep my code as clean as possible. Any other suggestions of how to tide up this snippet of code would be appreciated.
Aucun commentaire:
Enregistrer un commentaire