ArrayList迭代混乱

时间:2016-05-25 22:03:08

标签: java android arraylist

我的arraylist存在问题。

我有一个带鞋的arraylist。这些鞋可以有类别和价格:即智能鞋,休闲鞋等,但我想得到每个类别鞋的总量。

例如,如果我的arraylist有10个智能鞋,每个都有自己的价格和15个休闲鞋及其价格,我想只得到该类别和该类别的总数。

我有一个名为类别的arraylist,用于存储类别和类别所拥有的鞋子总数以及具有价格,鞋子和类别的收据arraylist。

float total = 0;

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

    for(int j = 0; j< receipts.size(); j++)
        if (TextUtils.equals(receipts.get(i).getCategory(), receipts.get(j).getCategory()))
            total += Float.parseFloat(receipts.get(j).getPrice());

    categories.add(new Category(receipts.get(i).getCategory(),String.valueOf(total)));
    total = 0;
}

此代码的问题是我倾向于获得一个类别的多个值。

1 个答案:

答案 0 :(得分:1)

如果您使用java 8,我建议使用lambda。例如,如果您有一个Shoe数组,则可以按类别分隔鞋子:

final List<Shoe> xShoes = collect.get(1);
final List<Shoe> yShoes = collect.get(2);

然后你可以获得你的偏好集合:

long priceX = xShoes.stream().map(Shoe::getPrice).reduce((aLong, aLong2) -> aLong + aLong2).get();
    long priceY = xShoes.stream().map(Shoe::getPrice).reduce((aLong, aLong2) -> aLong + aLong2).get();

您也可以通过以下方式获得总价:

shared_ptr
相关问题