如何将HashMap的键与字符串进行比较?Java HashMap检查文件中是否存在
我有100k行数的文本文件并将其放入HashMap中。
比如我的HashMap是这样的:
{test1=1}
{test2=2}
up to...
{test100000=100000}
而在另一方面,我读一本100万数量的文本文件的行。 文本文件具有数据是这样的:
test1,first,input1
test2,second,input2
up to..
test1000000,1million,input1million
,我分裂它与行“”我就是刚开行的第一个数据。这是“试字”,例如:
test1
test2
所以我想要做的是,我想检查我的HashMap的键在文本文件中存在的。
我的问题是,我的其他文本文件比我的HashMap的行大,所以它可能会抛出一个NullPointerException或NoSuchElement。
这里是我的代码:
public static void main(String[] args) {
File small = new File("C:\test\\testfolder\\small.txt"); // text file (100k+lines) put in hashmap
File large = new File("C:\test\\testfolder\\big.txt"); // text file (1million+ lines) just read
ArrayList<String> smallData= new ArrayList();
smallData.addAll(getData(small));
Map<String,String> smallMap = new HashMap();
smallMap = MapSmallFile(smallData);
try{
LineIterator it = FileUtils.lineIterator(large,"UTF-8");
String line;
String[] large_data;
while(it.hasNext()){
line = it.nextLine();
large_data = StringUtils.split(line, (","));
//do the comparing here
if(large_data[0].equalsIgnoreCase(?????)
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
private static ArrayList<String> getData(File file) {
ArrayList<String> data = new ArrayList();
String line;
try{
LineIterator it = FileUtils.lineIterator(file,"UTF-8");
while(it.hasNext()){
line = it.nextLine();
data.add(line);
}
it.close();
}
catch(Exception e){
e.printStackTrace();
}
return data;
}
private static Map<String,String> MapSmallFile(ArrayList<String> inputlist){
String[] data;
Map<String,String> hashmap = new HashMap<String,String>();
for(int i=0; i<inputlist.size(); i++){
data = inputlist.get(i).split(",");
hashmap.put(data[0], data[1]);
}
return hashmap;
}
哈希地图get方法没有抛出异常,则返回一个空值。 –
但事情是,我如何检查密钥是否存在于行中? – tuturyokgaming
@tutuyokgaming你可以使用'HashMap.keySet()'返回'List'并使用'List.contains'来检查。 –