簡體   English   中英

如何轉換為 <String, <List<String> &gt;轉換為String [] []?

[英]How do I convert a TreeMap that is a <String, <List<String>> to String[][]?

我不確定應該將數組String [][] ans初始化為什么。

如果我將其設置為treeMap的大小,則存在一個NPE。

String [][] ans = new String[size][];

因此,我將其初始化為大於預期的大小,但是數組中存在空值。

目前,我的treeMap為{C = [E],M = [F,B],S = [F,B],T = [F,B,L],TD = [E,L],W = [E, L],Z = [F]}

我希望它成為

[[C,E],[M,F,B],[S,F,B] ....]

import java.util.*;

public class Copy {
    public static String[][] oMI(String[][] m){

        //ans[0][0]= "test";
        Map<String, List<String>>  map  = new HashMap<>();
        int length = m.length;
        for (int i=0; i < m.length;i++){
            for (int j=1; j < m[i].length;j++){
                String key = m[i][j];

                map.computeIfAbsent(key, k-> new ArrayList<String>()).add(m[i][0]);
            }
        }
        Map<String,List<String>> treeMap = new TreeMap<String, List<String>>(map);
        System.out.println(treeMap);

        int size = treeMap.size();

        String [][] ans = new String[20][20];
        int l = 0;
        int s = 0;
        String ing = "";
        for (Map.Entry<String,List<String>> entry: treeMap.entrySet()){
            s = entry.getValue().size();

            if (entry.getKey() !=null)
                ing = entry.getKey();
            else ing ="null";

            ans[l][0] = ing;

            int mn = 0;
            for (String v : entry.getValue()) {
                ans[l][mn] = v;       
                l++;
                mn++;
            }
        }
        return ans;
    }

    public static void main(String[] args){

        String  [][] ma =
                {
                        {"F", "T", "Z", "S", "M"},
                        {"E", "C", "W", "TD"},
                        {"B", "M", "S", "T"},
                        {"L", "W", "T", "TD"}

                };
        oMI(ma);
    }
}

如果您需要不使用流的解決方案,則可以使用以下方法:

    int size = treeMap.size();
    String [][] ans = new String[size][]; //initialize the known dimension only
    int arrayRow = 0;
    for (Map.Entry<String,List<String>> entry: treeMap.entrySet()){

        int rowSize = entry.getValue().size() + 1;
        String[] tempArray = new String[rowSize]; //an temp array to hold key + vlaues
        tempArray[0] = entry.getKey();            //add key to temp array

        int mn = 1;
        for (String s : entry.getValue()) { tempArray[mn++] = s; } //add values to temp array
        ans[arrayRow++] = tempArray; //add temp array to output array
    }

    return ans;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM