计算和比较csv文件中的字符串

问题描述 投票:0回答:1

我有一个18000行的大csv文件。它们代表利口酒商店的不同种类的商品。如果我用bufferedReader拆分行,我会得到一些列,如文章编号,名称,酒量,价格等等。

在第七栏中是饮料的类型(啤酒,呜呜声朗姆酒等)。计算每种类型的文章数量的最佳方法是什么?我希望能够在不知道类型的情况下做到这一点。我只想使用java.util。*。

我可以通读该列并将其存储在队列中。在阅读时我将每种新类型存储在一个集合中。然后我可以比较队列中的所有元素到这个集合?

br = new BufferedReader(new FileReader(filename));
            while ((line = br.readLine()) != null) {

                // using \t as separator
                String[] articles = line.split(cvsSplitBy);

输出应该是这样的。

There are: 
100 beers
2000 whines 
etc. etc.

in the sortiment
java csv
1个回答
0
投票

您可以使用HashMap<String, integer>来了解您拥有的每个类别的产品数量。用法如下:

HashMap<String, Integer> productCount = new HashMap<>(); //This must be outsise the loop

//read you CSV here, this should be placed inside the loop
String product = csvColumns[6];
if(productCount.containsKey(product)) { //If the product doesn't exist
    productCount.put(product, 1);
} else { //Product exists, add 1
    int count = productCount.get(product);
    productCount.put(productCount, count+1);
}

免责声明您必须确保所有产品的名称相同,即:beerBeer。对于Java,这些是不同的字符串,因此,将有不同的计数。一种方法是将每个产品转换为大写,即:beer - > BEER Beer-> BEER。这将导致在显示结果时以大写形式显示所有名称。

© www.soinside.com 2019 - 2024. All rights reserved.