如何遍历泛型列表

时间:2018-07-19 05:44:51

标签: java loops java-8 iteration

我有一个类,其中有一个通用类型列表。现在,我尝试遍历该列表以获取该类的值。在getOrderAmount()方法中,我尝试进行迭代。

@Document(collection = Cart.FIELDS.COLLECTION)
public class Cart extends BaseOrderEntity {

    public interface FIELDS extends BaseOrderEntity.FIELDS {
        String COLLECTION = "cart";
        String LIST_ORDERS = "orderList";
        String CART_TYPE = "cartType";
    }

    @Field(value = FIELDS.LIST_ORDERS)
    private List<T> orderList;
    @Field(value = FIELDS.CART_TYPE)
    private Integer cartType;

    public List<T> getOrderList() {
        return orderList;
    }

    public void setOrderList(List<T> orderList) {
        this.orderList = orderList;
    }

    public Integer getCartType() {
        return cartType;
    }

    public void setCartType(Integer cartType) {
        this.cartType = cartType;
    }

    @Override
    public RefCollectionType getRefCollectionType() {
        if (T.class.getClass() == FoodItemOrderDetails.class.getClass()) {
            return RefCollectionType.FOOD;
        } else if (T.class.getClass() == LaundryItemOrderDetails.class.getClass()) {
            return RefCollectionType.LAUNDRY;

        } else if (T.class.getClass() == HousekeepingItemOrderDetails.class.getClass()) {
            return RefCollectionType.HOUSEKEEPING;

        }
        return RefCollectionType.FOOD;
    }

    @Override
    public double getOrderAmount() {
        double totalfoodOrderAmount = 0.0;
        for (FoodItemOrderDetails foodItem : orderList) {
            totalfoodOrderAmount = totalfoodOrderAmount + (foodItem.getPrice() * foodItem.getQuantity());
        }
        return totalfoodOrderAmount;
    }
}

通用类在这里。

FoodItemOrderDetails
LaundryItemOrderDetails
HousekeepingItemOrderDetails

1 个答案:

答案 0 :(得分:2)

您应该有一个类似OrderDetails的接口,该接口应该有两种方法getQuantity()getPrice()。现在,在FoodItemOrderDetails中实现该接口, LaundryItemOrderDetailsHousekeepingItemOrderDetails

    for (OrderDetails item : orderList) {
        totalAmount = totalAmount + (item .getPrice() * item.getQuantity());
    }

您的界面应如下所示。

interface OrderDetails {
    Double getPrice();

    Integer getQuantity();
}

您的课程如下所示。

class FoodItemOrderDetails implements OrderDetails {
    @Override
    public Double getPrice() {
        // return the price for FoodItem
        return null;
    }

    @Override
    public Integer getQuantity() {
        // return the Quantity for FoodItem
        return null;
    }
}

您可以使用Java-8流。

List<OrderDetails> details = new ArrayList<>();
double total = details.stream().mapToDouble(e -> e.getPrice() * e.getQuantity()).sum();