Java:合并 2 个列表 <String[]>

标签 java string list arrays

我有两个数组字符串列表。我希望能够通过组合这两个列表来创建一个新列表(newList)。但必须满足这3个条件:

1)将store_inventory的内容复制到newList中。

2) 然后,如果 store_inventory 和 new_acquisitions 中的商品名称匹配,只需将两个数量相加并在 newList 中更改即可。

3) 如果new_acquisitions有store_inventory中不存在的新商品,则将其添加到newList中。

CSV 列表的标题为:商品名称、数量、成本、价格。

列表包含每行的项目名称、数量、成本和价格的字符串[]。

    CSVReader from = new CSVReader(new FileReader("/test/new_acquisitions.csv"));
    List <String[]> acquisitions = from.readAll();

    CSVReader to = new CSVReader(new FileReader("/test/store_inventory.csv"));
    List <String[]> inventory = to.readAll();

    List <String[]> newList;

任何让我开始的代码都会很棒! =]

这就是我到目前为止所拥有的......

        for (int i = 0; i < acquisitions.size(); i++) {
        temp1 = acquisitions.get(i);
        for (int j = 1; j < inventory.size(); j++) {
            temp2 = inventory.get(j);
            if (temp1[0].equals(temp2[0])) {
                //if match found... do something?



                //break out of loop
            }
        }
        //if new item found... do something?
    }

最佳答案

我首先将 newList 构建为 HashMap 或 TreeMap 而不是 List。这使得搜索匹配记录变得容易。此外,我会将 String[] 转换为包含名称、数量、成本和价格字段的自定义对象(例如 Record)。这将负责复制信息。你可以尝试这样的事情:

Map<String, Record> newMap = new TreeMap<String, Record>();
for(String[] ss : acquisitions) {
    Record rec = Record.parse(ss); // For requirement (1)
    newMap.put(rec.getName(), rec);
}

for(String[] ss : inventory) {
    Record rec = Record.parse(ss); // For requirement (1)
    if(newMap.containsKey(rec.getName())) {
        // For requirement (2)
        // The mergeWith method can then add quantities together
        newMap.get(rec.getName()).mergeWith(rec);
    } else {
        // For requirement (3)
        newMap.put(rec.getName(), rec);
    }
}

编辑 使用 Record 对象的另一个优点是,通过实现 toString 函数可以更轻松地将其打印到屏幕上。

public class Record implements Comparable<Record> {
    public static Record parse(String[] ss) {
        // TODO: implement some basic parsing
    }

    private String name;
    private int quantity;
    private BigDecimal cost, price;

    private Record() {}

    public String getName() { return name; }
    public int getQuantity() { return quantity; }
    public BigDecimal getCost() { return cost; }
    public BigDecimal getPrice() { return price; }

    public int compareTo(Record other) {
        return this.name.compareTo(other.name);
    }

    public String toString() {
        return name;
    }
}

关于Java:合并 2 个列表 <String[]>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2983950/

相关文章:

ruby-on-rails - helpers 真的比 partials 快吗?弦乐 build 呢?

检查列表中不定# of consec 元素是否总和为给定值的 Pythonic 方法

list - 根据 Mathematica 中的另一个列表值拆分列表

java - 从数组实例调用 get(数组静态方法)

java - 水平循环Map<String, List<String>>并设置javabean的变量

java - (Java) 删除 ArrayList 元素会在内存中腾出更多空间吗?

Python 正则表达式搜索不适用于包含冒号的字符串(:)

java - 如何删除文件夹及其子文件夹中的所有文件?

javascript - 如何比较字符串字母(javascript)

python - CSV Python 列表