繁体   English   中英

如何检查arrayList中的项是否已经存在并在Java中添加计数?

[英]How to check if an item in an arrayList already exists and add count in Java?

假设我有一个Groceries(name,quantity)Groceries(name,quantity)并且该类用于一个名为shoppingList的数组列表。

   ArrayList<Groceries> shoppingList = new ArrayList<>();

项目的名称和数量将存储在此阵列列表中。 即将添加到此arrayList中的项目已经存在,但数量不同。 如何通过绕过已经存在的名称来避免重复,而只是将数量添加到已存在的名称中,如何避免重复?

这是我的代码,我尚未完成:应该从数据文件中读取

add,3,loaf of bread
add,2,jug of milk
list
buy,2,loaf of bread
add,4,loaf of bread
buy,3,jug of milk

import java.io.*;
import java.util.ArrayList;
public class A3Q1 {
    public static void main(String[] args){
        BufferedReader input;
        String line;
        String command, name;
        int quantity;
        //Groceries name;
        String tokens[];

        ArrayList<Groceries> shoppingList = new ArrayList<>();
        ArrayList<Groceries> purchaseList = new ArrayList<>();
        Groceries grocery;


        try{
            input = new BufferedReader(new FileReader("a3a.txt"));
            line = input.readLine();
            while(line!= null){
                tokens = line.split(",");
                command = tokens[0].trim();
                quantity = Integer.parseInt(tokens[1].trim());
                name = tokens[2].trim();

                if (command.equals("add")){
                    shoppingList.add(new Groceries(quantity,name));
                    if (command.equals("buy")){
                        purchaseList.add(new Groceries(quantity,name));
                    }
                }

            }

        }catch(IOException ioe){
            System.out.println(ioe.getMessage());
        }
    }
}

class Groceries {
    private String name;
    private int quantity;


    public Groceries( int quantity, String name){
        this.name =name;
        this.quantity=quantity;
    }


}

要求的要求;

用作程序输入的数据文件将由包含三个命令之一的行组成。 其中第一个是添加,其后是数量和商品名称,以逗号分隔。 这将添加到购物清单中; 如果已经存在具有该名称的项目,则将所需数量增加给定数字。 否则,将具有该名称和数量的新项目添加到列表中。 第二个命令是购买,后跟数量和物料名称。 这将以类似的方式添加到购买清单中。 另外,如果购物清单中已经有该名称的商品,请减少所需数量。 如果该商品的数量达到零(或更少),请从购物清单中将其删除。 最后,list命令应打印出两个列表,同时显示数量和项目名称,每行显示一个项目。 例如,数据文件:

改用HashMap:

Map<String, Integer> shoppingList = new HashMap<>();
shoppingList.put("Eggs", 1);

// Add more
if(shoppingList.containsKey("Eggs")){
  shoppingList.put("Eggs", shoppingList.get("Eggs") + 5);
}

您现在可以轻松访问特定的杂货,避免重复。 当然,如果它具有比“ name”属性更多的属性,则也可以使用Groceries类代替String。

您可以使用ArrayListindexOf(Object o)方法获取列表中杂货店的索引,如果它返回有效值(即大于-1),请使用get(int index)检索Groceries对象并递增/替换其数量。


可能的陷阱和有趣的事情

我不知道您的Groceries类的实现详细信息,但您应该注意,如果您为相同的杂货店(即,具有相同名称)创建新的Groceries对象,并且不覆盖equals(Object obj)可能hashCode()方法也是如此,因为“相等的对象必须具有相等的哈希码” )方法,所以在将对象与它们的equals方法进行比较时,您将永远不会在列表中找到重复项。

如果您确实只想存储Groceries对象并强制列表中只能有一个相同的对象,则应该使用Set (特别是HashSet )。 仍然要记住,您必须重写equalshashCode

好吧,如您所愿,请使用ArrayList而不与HashMap或其他键值类混合使用,您将需要通过循环检查杂货店是否存在,如果存在,则需要将其删除并添加数量增加的新杂货店。

您也有一些代码错误,请仔细阅读下面的代码,并尝试理解它。 这是最好的学习方式! 不只是复制和粘贴;)

import java.io.*;
import java.util.ArrayList;

public class A3Q1 {
    public static void main(String[] args){
        BufferedReader input;
        String line;
        String command, name = null;
        int quantity = 0;
        //Groceries name;
        String tokens[];

        ArrayList<Groceries> shoppingList = new ArrayList<>();
        ArrayList<Groceries> purchaseList = new ArrayList<>();
        Groceries grocery = null;


        try{
            input = new BufferedReader(new FileReader("a3a.txt"));
            line = input.readLine();
            while(line!= null){
                tokens = line.split(",");
                command = tokens[0].trim();

                if(command.equals("list")) {
                  System.out.println("shoppingList " + shoppingList);
                  System.out.println("purchaseList " + purchaseList);
                  System.out.println("");
                } else {
                  quantity = Integer.parseInt(tokens[1].trim());
                  name = tokens[2].trim();
                }

                if (command.equals("add")) {
                  boolean added = false;
                  for (int i=0; i<shoppingList.size(); i++) {
                    Groceries g = (Groceries) shoppingList.get(i);
                    if( g.getName().equals(name) ){
                      shoppingList.remove(g);
                      quantity += g.getQuantity();
                      g.setQuantity(quantity);
                      shoppingList.add(g);
                      added = true;
                      break;
                    }
                  }
                  if( !added ) {
                    shoppingList.add(new Groceries(quantity,name));
                  }
                }
                if (command.equals("buy")) {
                  for (int i=0; i<shoppingList.size(); i++) {
                    Groceries g = (Groceries) shoppingList.get(i);
                    if( g.getName().equals(name) ){
                      shoppingList.remove(g);
                      if( g.getQuantity() - quantity > 0 ) {
                        g.setQuantity(g.getQuantity() - quantity);
                        shoppingList.add(g);
                      } else {
                        //quantity = g.getQuantity(); //removed this as you wanted to keep the purchaselist this way
                      }
                      break;
                    }
                  }

                  boolean added = false;
                  for (int i=0; i<purchaseList.size(); i++) {
                    Groceries g = (Groceries) purchaseList.get(i);
                    if( g.getName().equals(name) ){
                      purchaseList.remove(g);
                      quantity += g.getQuantity();
                      g.setQuantity(quantity);
                      purchaseList.add(g);
                      added = true;
                      break;
                    }
                  }
                  if( !added ) {
                    purchaseList.add(new Groceries(quantity,name));
                  }
                }
                line = input.readLine();
            }

        }catch(IOException ioe){
            System.out.println(ioe.getMessage());
        }
    }
}

class Groceries {
    private String name;
    private int quantity;


    public Groceries( int quantity, String name){
        this.name =name;
        this.quantity=quantity;
    }

    public String getName() {
      return name;
    }

    public int getQuantity() {
      return quantity;
    }

    public void setQuantity(int quantity) { this.quantity=quantity; }

    public String toString() {
      return quantity + ", " + name;
    }
}

a3a.txt

add,3,bread
list
add,2,milk
list
buy,2,bread
list
add,4,bread
list
buy,3,milk
list
buy,1,butter
list

(我假设list是将显示列表的命令)

输出量

shoppingList [3, bread]
purchaseList []

shoppingList [3, bread, 2, milk]
purchaseList []

shoppingList [2, milk, 1, bread]
purchaseList [2, bread]

shoppingList [2, milk, 5, bread]
purchaseList [2, bread]

shoppingList [5, bread]
purchaseList [2, bread, 3, milk]

shoppingList [5, bread]
purchaseList [2, bread, 3, milk, 1, butter]
void addGroceries(String item,Integer quantity, Map<String,Integer> shoppingList){
                    if(shoppingList.containsKey(item)){
                  Integer newQuatity =shoppingList.get(item);
                  shoppingList.remove(item);
                  shoppingList.put(item, quatity+newQuatity);
                }
                 else{
               shoppingList.put(item, quatity);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM