0

我正在尝试在此数据中创建一个 csv 文件,并将其存储为键值对并正确显示值。如何将键显示为字段的标题(值)

 for (Map<String, String> map : test) {          
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String,String> mapEntry = (Map.Entry<String,String>) iterator.next();
           //System.out.println("key: " + mapEntry.getKey() + ", value:" + mapEntry.getValue());

            writer.append(mapEntry.getValue());
            writer.append(",");
            iterator.remove();
        }
        writer.append("\n");
        }
        writer.flush();
        writer.close();
    }
4

2 回答 2

0

在你的 for 循环中试试这个代码:

 Collection<String> kys = map.keySet();
            Collection<String> vls = map.values();
            for (String k : kys) {
                 writer.append(k);
                    writer.append(",");
            }
            writer.append("\n");

            for (String v : vls) {
                 writer.append(v);
                    writer.append(",");
            }

            writer.flush();
            writer.close();
于 2013-10-17T08:56:52.417 回答
0

寻找这样的东西?

package com.stackoverflow.csv;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class CreateFile {

    public static final String LINE_BREAK = "\n";
    public static final String QUOTE = "\"";
    private final StringBuilder sb;
    public CreateFile(Map<String, String> table) {
        sb = new StringBuilder();
        Iterator<String> keys = table.keySet().iterator();

        while (keys.hasNext()){
            sb.append(QUOTE + keys.next() + QUOTE);
            if (keys.hasNext())
                sb.append(", ");
        }
        sb.append(LINE_BREAK);
        Iterator<String> entries = table.values().iterator();
        while (entries.hasNext()) {
            sb.append(QUOTE + entries.next() + QUOTE);
            if (entries.hasNext())
                sb.append(", ");
        }
    }
    public String getCSV() {
        return sb.toString();
    }

    public static void main(String[] args) {
        HashMap<String,String> map = new HashMap<>();
        map.put("KEY1", "VALUE1");
        map.put("KEY2", "VALUE2");
        map.put("KEY3", "VALUE3");
        map.put("KEY4", "VALUE4");
        map.put("KEY5", "VALUE5");
        map.put("KEY6", "VALUE6");
        map.put("KEY7", "VALUE7");
        map.put("KEY8", "VALUE8");
        map.put("KEY9", "VALUE9");
        map.put("KEY10", "VALUE10");
        CreateFile app = new CreateFile(map);
        System.out.println(app.getCSV());
    }
}
于 2013-10-17T09:11:24.357 回答