Java - Write hashmap to a csv file

前端 未结 6 1744
忘了有多久
忘了有多久 2020-12-06 18:29

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 | a         


        
6条回答
  •  臣服心动
    2020-12-06 19:03

    If you have a single hashmap it is just a few lines of code. Something like this:

    Map myMap = new HashMap<>();
    
    myMap.put("foo", "bar");
    myMap.put("baz", "foobar");
    
    StringBuilder builder = new StringBuilder();
    for (Map.Entry kvp : myMap.entrySet()) {
        builder.append(kvp.getKey());
        builder.append(",");
        builder.append(kvp.getValue());
        builder.append("\r\n");
    }
    
    String content = builder.toString().trim();
    System.out.println(content);
    //use your prefered method to write content to a file - for example Apache FileUtils.writeStringToFile(...) instead of syso.    
    

    result would be

    foo,bar
    baz,foobar
    

提交回复
热议问题