如何将java映射转换为分隔格式

如何将java映射转换为分隔格式,java,dictionary,map,Java,Dictionary,Map,例如: key1: 1,2,3,4 key2: 5,6 将转换为 key1|key2 1|5 2|6 3 4 我知道,如果我们反复地这样做,有很多方法是无效的。我想知道是否有任何内置的方法或任何东西可以直接转换它们 HashMap<String, String> h1 = new HashMap<String, String>; h1.put("key1", "1,2,3,4"); h1.put("key2", "5,6"); 这将完成转换。代码看起来很长很复杂,

例如:

key1: 1,2,3,4
key2: 5,6
将转换为

key1|key2
1|5
2|6
3
4
我知道,如果我们反复地这样做,有很多方法是无效的。我想知道是否有任何内置的方法或任何东西可以直接转换它们

HashMap<String, String> h1 = new HashMap<String, String>;
h1.put("key1", "1,2,3,4"); 
h1.put("key2", "5,6");

这将完成转换。代码看起来很长很复杂,但总体复杂度仍然是O(n):无论贴图大小,每个键和值都会被固定次数地触摸

public static void main(final String[] args) {
    Map<String, String> map = getMap();
    Map<String, String[]> map2 = new TreeMap<>();

    // (1) Read the map into an intermediate map and
    // get the number of rows needed
    int maxSize = 0;
    for (Map.Entry<String, String> entry : map.entrySet()) {
        String[] array = entry.getValue().split(",");
        maxSize = array.length > maxSize ? array.length : maxSize;
        map2.put(entry.getKey(), array);
    }

    // (2) prepare the table structure
    List<List<String>> table = new ArrayList<>();
    for (int i = 0; i < (maxSize + 1); i++) {
        table.add(new ArrayList<String>());
    }

    // (3) read the values into the table structure
    for (Map.Entry<String, String[]> entry : map2.entrySet()) {
        table.get(0).add(entry.getKey());
        for (int i = 0; i < maxSize; i++) {
            if (i < entry.getValue().length) {
                table.get(i + 1).add(entry.getValue()[i]);
            } else {
                table.get(i + 1).add("");
            }
        }
    }

    // (4) dump the table
    for (List<String> row : table) {
        StringBuilder rowBuilder = new StringBuilder();
        boolean isFirst = true;
        for (String value : row) {
            if (isFirst) {
                isFirst = false;
            } else {
                rowBuilder.append('|');
            }
            rowBuilder.append(value);
        }
        System.out.println(rowBuilder.toString());
    }

}

private static Map<String, String> getMap() {
    Map<String, String> map = new TreeMap<>();
    map.put("key1", "1,2,3,4");
    map.put("key2", "5,6");
    map.put("key3", "7,8,9");
    return map;
}

(第一个答案,基于错误的猜测)

假设5和6是键1和键2的值,那么这是一个很好的解决方案:

public static void dumpMap(Map<String, String> map) {
    for (Map.Entry<String, String> entry:map.entrySet()) {
        System.out.printf("%s|%s%n", entry.getKey(), nullSafe(entry.getValue()));
    }
}

private static String nullSafe(String value) {
    return value == null ? "" : value;
}
publicstaticvoiddumpmap(映射映射){
对于(Map.Entry:Map.entrySet()){
System.out.printf(“%s |%s%n”,entry.getKey(),nullSafe(entry.getValue());
}
}
私有静态字符串nullSafe(字符串值){
返回值==null?“:值;
}
它是O(n),我们不能更有效地执行它,因为我们必须访问每个键/值对一次才能打印它


(除非我们可以使用并行计算;)

您可以使用这样的类:

import java.util.*;

class LegacyGlueifier
{
    private LegacyGlueifier()
    {
    }

    public static String generateLegacyDataset(Map<String, String> data)
    {
        final ArrayList<ArrayList<String>> lists = new ArrayList<ArrayList<String>>();
        final int width = data.size();

        int i = 0;
        for (Map.Entry<String, String> entry : data.entrySet())
        {
            String[] values = entry.getValue().split(",");
            changeDims(lists, width, values.length + 1);

            for (int j = 0; j < values.length; ++j) setValue(lists, j + 1, i, values[j]);
            setValue(lists, 0, i, entry.getKey());
            ++i;
        }

        return stringify(lists);
    }

    private static void changeDims(ArrayList<ArrayList<String>> lists, int width, int newHeight)
    {
        while (lists.size() < newHeight) lists.add(arrayListOfSize(width));
    }

    private static ArrayList<String> arrayListOfSize(int w)
    {
        ArrayList<String> list = new ArrayList<String>(w);
        while (list.size() < w) list.add(null);
        return list;
    }

    private static void setValue(ArrayList<ArrayList<String>> lists, int row, int col, String val)
    {
        ArrayList<String> temp = lists.get(row);
        temp.set(col, val);
        // System.out.println("SET: " + row + " " + col + ": " + val);
    }

    private static String swapNullWithEmpty(String s)
    {
        if (s == null) return "";
        return s;
    }

    private static String stringify(ArrayList<ArrayList<String>> lists)
    {
        StringBuilder sb = new StringBuilder();
        for (ArrayList<String> sublist : lists)
        {
            if (sublist.size() != 0) sb.append(swapNullWithEmpty(sublist.get(0)));
            for (int i = 1; i < sublist.size(); ++i)
                sb.append("|").append(swapNullWithEmpty(sublist.get(i)));
            sb.append("\n");
        }

        return sb.toString();
    }
}
import java.util.*;
类糊化剂
{
私人立法机构()
{
}
公共静态字符串generateLegacyDataset(地图数据)
{
最终的ArrayList,但我仍然会更彻底地测试它,因为您将要使用它


它的时间复杂度介于原始数据集中逗号分隔字段的总数与输出数据集中字段(包括空白字段)的总数之间。

您的问题不清楚-请澄清输入是什么。(您的标题显示地图,但
key1:1,2,3,4 key2:5,6
看起来不像地图)。您是否只有两个
键?这可能是一个映射吗?不要混淆效率和简洁性。手动编码的迭代非常有效,在许多情况下,如果需要任何类型的转换,都比使用库方法要好。当您引入
键3:7,8,9,10时会发生什么?您为什么要这样做不,映射就像
{“key1”:“1,2,3,4”,“key2”:“5,6”}
一样。这并不是那么简单,你必须并行迭代所有值(解析后)并根据映射条目的数量创建printf模板。Marko,在Victor向我们展示映射的真实外观之前,我已经创建了答案。我在看到这一点之前也发表了评论:)我只是基于最初的电子表格样式显示。很抱歉有任何混淆,实际上是的,输出应该是列格式
public static void dumpMap(Map<String, String> map) {
    for (Map.Entry<String, String> entry:map.entrySet()) {
        System.out.printf("%s|%s%n", entry.getKey(), nullSafe(entry.getValue()));
    }
}

private static String nullSafe(String value) {
    return value == null ? "" : value;
}
import java.util.*;

class LegacyGlueifier
{
    private LegacyGlueifier()
    {
    }

    public static String generateLegacyDataset(Map<String, String> data)
    {
        final ArrayList<ArrayList<String>> lists = new ArrayList<ArrayList<String>>();
        final int width = data.size();

        int i = 0;
        for (Map.Entry<String, String> entry : data.entrySet())
        {
            String[] values = entry.getValue().split(",");
            changeDims(lists, width, values.length + 1);

            for (int j = 0; j < values.length; ++j) setValue(lists, j + 1, i, values[j]);
            setValue(lists, 0, i, entry.getKey());
            ++i;
        }

        return stringify(lists);
    }

    private static void changeDims(ArrayList<ArrayList<String>> lists, int width, int newHeight)
    {
        while (lists.size() < newHeight) lists.add(arrayListOfSize(width));
    }

    private static ArrayList<String> arrayListOfSize(int w)
    {
        ArrayList<String> list = new ArrayList<String>(w);
        while (list.size() < w) list.add(null);
        return list;
    }

    private static void setValue(ArrayList<ArrayList<String>> lists, int row, int col, String val)
    {
        ArrayList<String> temp = lists.get(row);
        temp.set(col, val);
        // System.out.println("SET: " + row + " " + col + ": " + val);
    }

    private static String swapNullWithEmpty(String s)
    {
        if (s == null) return "";
        return s;
    }

    private static String stringify(ArrayList<ArrayList<String>> lists)
    {
        StringBuilder sb = new StringBuilder();
        for (ArrayList<String> sublist : lists)
        {
            if (sublist.size() != 0) sb.append(swapNullWithEmpty(sublist.get(0)));
            for (int i = 1; i < sublist.size(); ++i)
                sb.append("|").append(swapNullWithEmpty(sublist.get(i)));
            sb.append("\n");
        }

        return sb.toString();
    }
}