如何将java Map转换为分隔格式

时间:2012-11-06 14:21:36

标签: 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|key2
1|5
2|6
3
4

2 个答案:

答案 0 :(得分:0)

这将进行转型。代码看起来很复杂,但整体复杂性仍然是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;
}

此样本的结果是:

key1|key2|key3
1|5|7
2|6|8
3||9
4||

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

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

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;
}

它是O(n),我们不能更有效率,因为我们必须访问每个键/值对一次才能打印出来。

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

答案 1 :(得分:0)

您可以使用类似这样的类:

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();
    }
}

调用是String dataset = LegacyGlueifier.generateLegacyDataset(myMap)

I ran it through a basic test case to see if it worked但是我会继续测试它,因为你将要使用它。

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