[我正在尝试使用CSVREADER将hash1的col1值映射到csv文件中的col2值。但是我找不到这样做的逻辑。
我想通过CSVReader读取CSV,循环数据线并使用arraylist和hashmap键以及value(arraylist)来实现。我不想对其进行硬编码。
我做了一些事情直到以下。无法继续进行。请帮助..
CSVReader csvReader = new CSVReader(new FileReader(fileName),',','"',1);
Map<String, List<String>> tableandcols = new HashMap<String, List<String>>();
ArrayList<String> tablenames = new ArrayList<>();
ArrayList<String> colnames = new ArrayList<>();
while((row = csvReader.readNext()) != null) {
tablenames.add(row[0]);
colnames.add(row[1]);
}
input data:
State,City,Country
NJ,Trenton,US
NJ,Newark,US
NC,Cary,US
NC,Charlotte,US
GA,Atlanta,US
I want the data to be in hashmap as following
[<NJ,[Trenton,Newark]>
<NC,[Cary,Charlotte]>
<GA,[Atlanta]>]
您可以尝试下面的代码:
try
{
CSVReader csvReader = new CSVReader(new FileReader(fileName),',','"',1);
Map<String, List<String>> tableandcols = new HashMap<String, List<String>>();
while((row = csvReader.readNext()) != null)
{
// If map contains state already, add the city to the values list
if(tableandcols.containsKey(row[0]))
{
tableandcols.get(row[0]).add(row[1);
}
// if map doesn't have this state as key, insert a key and value
else {
List<String> cities = new ArrayList<>();
cities.add(row[1]);
tableandcols.put(row[0], cities);
}
}
}
catch(Exception e){
// log exception
}