Chrometobia Chrometobia - 6 months ago 11
Java Question

ArrayList iterration confussion

I have an issue with my arraylist.

I have an arraylist with shoes. These shoes can be have categories and prices: that is smart shoes, casual shoes and so on, but I want to get the total amount of shoes per category.

For example, if my arraylist has 10 smart shoes each with its own price and 15 casual shoes with their prices respectively, I want to get only the category and how much each total that category has.

I have an arraylist called category that stores a category and the total amount of of shoes that category has and a receipt arraylist that has the price, shoe, and category.

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;
}


The issue with this code is I tend to get multiple values of one category.

Answer

If you use java 8, I recommend use lambda. For example, if you have an array of Shoe, you can separate the shoes by category:

ArrayList<Shoe> receipts = new ArrayList<>();

final Map<Long, List<Shoe>> collect = receipts.stream().collect(Collectors.groupingBy(Shoe::getIdCategory));

Then you can get the collection of you preference:

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

And also you can get the total price with:

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();
Comments