java map 批量写到 csv,Java - 将hashmap写入csv文件

I have a hashmap with a String key and String value. It contains a large number of keys and their respective values.

For example:

key | value

abc | aabbcc

def | ddeeff

I would like to write this hashmap to a csv file such that my csv file contains rows as below:

abc,aabbcc

def,ddeeff

I tried the following example here using the supercsv library: http://javafascination.blogspot.com/2009/07/csv-write-using-java.html. However, in this example, you have to create a hashmap for each row that you want to add to your csv file. I have a large number of key value pairs which means that several hashmaps, with each containing data for one row need to be created. I would like to know if there is a more optimized approach that can be used for this use case.

Thanks in advance!

解决方案

As your question is asking how to do this using Super CSV, I thought I'd chime in (as a maintainer of the project).

I initially thought you could just iterate over the map's entry set using CsvBeanWriter and a name mapping array of "key", "value", but this doesn't work because HashMap's internal implementation doesn't allow reflection to get the key/value.

So your only option is to use CsvListWriter as follows. At least this way you don't have to worry about escaping CSV (every other example here just joins with commas...aaarrggh!):

@Test

public void writeHashMapToCsv() throws Exception {

Map map = new HashMap<>();

map.put("abc", "aabbcc");

map.put("def", "ddeeff");

StringWriter output = new StringWriter();

try (ICsvListWriter listWriter = new CsvListWriter(output,

CsvPreference.STANDARD_PREFERENCE)){

for (Map.Entry entry : map.entrySet()){

listWriter.write(entry.getKey(), entry.getValue());

}

}

System.out.println(output);

}

Output:

abc,aabbcc

def,ddeeff

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值