如何在Java中映射<string,integer>两个csv列的值?

时间:2018-05-18 14:20:13

标签: java csv hashmap

我是Java中的新蜜蜂,想根据它们的值映射CSV列。 我的orignal csv数据如下:

//loops through all of the min x position indexes, and sets min x position at index i the the value of min x at index k
for (var i = 0; i < minXPosition.Length; i++)
{
    //checks if i is not zero and if it can be divided evenly by 8
    if ((i != 0) && (i % 8 == 0))
    {
        k++;
    }
    minXPosition[i] = minX[k];
}

预期输出应该是Hashmap Key Value对的两列名称和工资,如:

 name,salary,address
 AAA,1000,kkk
 BBB,880,lll
 AAA,90,kkk
 CCC,700,mmm
 BBB,700,lll

这是我的代码:

Key: AAA Value 1090
Key: BBB Value 1580
Key: CCC Value 700

1 个答案:

答案 0 :(得分:0)

您想要的是将您的行数据分成几部分。然后将其累积到Map

Map<String, Integer> result = new HashMap<>();

while ((line = b.readLine()) != null) {
   String[] parts = line.split(","); // Split your line, take `,` as delimeter
   String key = parts[0]; // This is your 'AAA'
   Integer value = Integer.parseInt(parts[1]); // This is your 1000
   if (result.get(key) == null) {
       result.put(key, value); 
   } else {
       result.put(key, result.get(key) + value); // There's already a value here, add it with new value
   }


}

丑陋的部分:

   if (result.get(key) == null) {
       result.put(key, value); 
   } else {
       result.put(key, result.get(key) + value); // There's already a value here, add it with new value
   }

可以替换为新的Java 8 Map实用程序:

 result.putIfAbsent(key, value); // Put (key, value) if key is absent from the map
 result.compute(key, value, (k, v) -> v + value);