计算列表中元素的出现次数

时间:2016-01-26 17:19:42

标签: java list hashmap

我正在尝试制作一个列表,我会将商品添加到我的购物车中,然后在结帐时,它会显示使用HashMap有多少件商品。

public class ShoppingCart 
{
    private ArrayList<Items> ShoppingCart;

    public ShoppingCart()
    {
        ShoppingCart = new ArrayList<Items>();
    }

    public void addItems(Items newItems)
    {
        ShoppingCart.add(newItems);
    }

    public ArrayList<Items> getShoppingCart()
    {
        return ShoppingCart;
    }

    public void CheckOut()
    {
        for(int i = 0; i < ShoppingCart.size(); i++)
        {
                HashMap<String, Integer> itemsMap = new HashMap<String, Integer>();
                int a = 1;

                if (itemsMap.containsKey(ShoppingCart.get(i).getName()))
                {
                    itemsMap.replace(ShoppingCart.get(i).getName(), a, a++);
                } 
                else 
                {
                    itemsMap.put(ShoppingCart.get(i).getName(), a);
                }
            System.out.println(a +"x "+ShoppingCart.get(i));
        }
    }

我的项目是用

创建的
public class Items 
{
    private String name;

    public Items (String name)
    {
        this.name = name;
    }

    public String toString()
    {
        return name;
    }

    public String getName()
    {
        return name;
    }

}

在Main中,我会创建Items,然后将它们添加到购物车,然后ShoppingCart.CheckOut();我的物品。

但是,如果我这样添加4个“白面包”,

    Items bread = new Items("White Bread");

    ShoppingCart ShoppingCart = new ShoppingCart();

    ShoppingCart.addItems(bread);
    ShoppingCart.addItems(bread);
    ShoppingCart.addItems(bread);
    ShoppingCart.addItems(bread);

我得到了

1x White Bread
1x White Bread
1x White Bread
1x White Bread 

而不是

4x White Bread

我做错了什么?

4 个答案:

答案 0 :(得分:5)

更改

itemsMap.replace(ShoppingCart.get(i).getName(), a, a++);

a = itemsMap.get(ShoppingCart.get(i).getName()); // in order to increment the 
                                                 // current counter value
itemsMap.replace(ShoppingCart.get(i).getName(), a, ++a);

使用帖子减量(a++)不会修改地图中的值,因为a++会返回原始值a

此外,HashMap应在循环外初始化。否则它将始终只包含一个元素。

答案 1 :(得分:0)

提前计算并打印总和:

    Map<String, Integer> itemsMap = new LinkedHashMap<String, Integer>();    
    for(int i = 0; i < ShoppingCart.size(); i++)
    {

            itemsMap.merge(ShoppingCart.get(i).getName(), 1, (old, set) -> old+set);
    }

    for (Map.Entry <String, Integer> e: itemsMap.entrySet ()) {
        System.out.println(e.getValue ()+"x "+e.getKey ());
    }

答案 2 :(得分:0)

2个主要问题: - 在每次迭代时都会创建HashMap,因此您之前无法使用地图中的任何内容。 - 您在FOR中的系统输出语句,因此您将获得与循环中的元素一样多的行。

为什么不使用地图来存储这样的项目?

public class ShoppingCart {

Map<Items, Integer> shoppingCart = new HashMap<>();

public ShoppingCart() {
}

public void addItems(Items newItem) {
    int count = shoppingCart.containsKey(newItem) ? shoppingCart.get(newItem) : 0;
    shoppingCart.put(newItem, ++count);
}

public List<Items> getShoppingCart() {
    return shoppingCart.keySet()
        .stream()
        .flatMap(item -> Collections.nCopies(shoppingCart.get(item), item).stream())
        .collect(Collectors.toList());
}

public void CheckOut() {
    for (Map.Entry<Items, Integer> entry : shoppingCart.entrySet()) {
        System.out.println(String.format("%dx %s", entry.getValue(), entry.getKey().getName()));
    }
}

public static class Items
{
    private String name;

    public Items (String name)
    {
        this.name = name;
    }

    public String toString()
    {
        return name;
    }

    public String getName()
    {
        return name;
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if(obj instanceof Items) {
            return name.equals(((Items)obj).getName());
        }
        return false;
    }
}

public static void main(String[] args) {
    Items bread = new Items("White Bread");

    ShoppingCart ShoppingCart = new ShoppingCart();

    ShoppingCart.addItems(bread);
    ShoppingCart.addItems(bread);
    ShoppingCart.addItems(bread);
    ShoppingCart.addItems(bread);

    ShoppingCart.CheckOut();
    System.out.println(ShoppingCart.getShoppingCart());
}

}

答案 3 :(得分:0)

我相信您的问题是您要为购物清单中的每件商品创建一个新的hashmap,请尝试以下方法:

    public void CheckOut()
{
    HashMap<String, Integer> itemsMap = new HashMap<String, Integer>();
    for(int i = 0; i < ShoppingCart.size(); i++)
    {
        if (itemsMap.containsKey(ShoppingCart.get(i).getName()))
        {
            itemsMap.put(ShoppingCart.get(i).getName(), itemsMap.get(ShoppingCart.get(i).getName())+1);
        } 
        else 
        {
            itemsMap.put(ShoppingCart.get(i).getName(), 1);
        }
    }
    Iterator it = itemsMap.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getValue()+"x " + pair.getKey() );
    }
}