我有两个文件input1.csv和input2.csv,它们的大小很大。
input1.csv具有三列A,B和C(B在此文件中是唯一的)。
input2.csv具有2列B和C。
我想检查在input2.csv文件中每次出现B的次数。
我已经实现了通过将input1.csv文件中的值B存储在arraylist中并使用哈希图将key作为B的值并将value作为B在input2.csv文件中的出现的方法。这种逻辑工作正常,但是当文件大小增加时执行时间也会增加。此外,还已经完成了main方法本身中的代码。还有其他逻辑可以解决这个问题吗???既然我是java的新手,那么有人可以为我提供一种很好的设计模式来解决这个问题吗?
程序:
import java.io.*;
import java.util.*;
public class Demo {
public static void main(String[] args) throws IOException{
BufferedReader reader = null;
String encoding = "UTF-8";
String comma = ",";
Map<String,Integer> hashMap = new HashMap<>();
ArrayList<String> arrayList = new ArrayList<String>();
reader = new BufferedReader(new InputStreamReader(new FileInputStream("input1.csv"), encoding));
for (String line; (line = reader.readLine()) != null;) {
String val = line.split(comma)[1];
arrayList.add(val); //Value to be later used
hashMap.put(val,0);
}
reader.close();
reader = new BufferedReader(new InputStreamReader(new FileInputStream("input2.csv"), encoding));
for (String line; (line = reader.readLine()) != null;) {
String val = line.substring(0,line.indexOf(","));
if(hashMap.get(val) !=null) {
hashMap.put(val, hashMap.get(val) + 1);
}
}
reader.close();
printMap(hashMap);
}
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
}
您的代码或多或少都可以。我不认为您可以做得更好。
一些评论:
arrayList
。如果您确实需要检查第二个文件中的值是否存在于第一个文件中,则应创建一个has set并检查contains
--但仅当遇到新值时才进行检查。hashMap.get(val)
,然后hashMap.put(val, hashMap.get(val) + 1)
)。仅保存hashMap.get(val)
在变量中将删除其中一个访问。AtomicInteger
值。你可能避免hashMap.put
只由incrementAndGet
该值。AtomicInteger
你就可以了hashMap.putIfAbsent(value, new AtomicInteger(0)).incrementAndGet()
。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句