将hashmap中的列表转换为2d数组

时间:2015-10-19 17:40:49

标签: java arrays linked-list hashmap

所以我的哈希映射定义为:hashmap<String,LinkedList<node>>。 节点类包含两个字段a和b。

我有很多字符串值需要我提供信息。 我想要做的是浏览hashmap并查找与我所拥有的每个值相关联的Linkedlists,并将字段'a'的列表变为二维数组。

所以字符串值“animal”的所有'a'字段都是2d数组中的第一个数组。字符串中的所有“a”字段值“人类”都在第二个数组中,依此类推。

我知道这种情况很糟糕,但我希望你明白这一点。

1 个答案:

答案 0 :(得分:0)

你应该考虑使用List列表而不是2D数组,因为我确定行和列非常好,你可能不知道每个的初始大小。

我做了一些假设,因为你没有指定。您可以根据需要进行修改,以适合您的特定方案。见下面的假设。

  

假设

  1. &#34; Strings&#34;你关心的是&#34; Animal&#34;,&#34; Human&#34;是hashMap
  2. 的关键字
  3. a类中的字段Node属于String
  4. 类型
  5. 您有所关注的所有字符串的列表
  6.   

    实施

    public static void main(String[] args) throws URISyntaxException, IOException {
        Map<String, LinkedList<Node>> hashMap = new HashMap<String, LinkedList<Node>>();
        List<List<String>> multiDemList = new ArrayList<List<String>>(); //Once the method is done this will contain your 2D list
        List<String> needInfoOn = new ArrayList<String>(); //This should contain all of the HashMap Keys you are interested in i.e. Animal, Human keys
    
        for(String s: needInfoOn){
            if(!hashMap.containsKey(s)) continue; //if the map doesnt contain this string then skip to the next so we dont add empty rows in our multidimensional array. remove this line if you want empty rows
            List<String> list = BuildTypeAList(hashMap, s);
            multiDemList.add(list);
        }
    }
    
    private static List<String> BuildTypeAList(Map<String, LinkedList<Node>> map, String s) {
        LinkedList<Node> linkedList = map.get(s);
        ArrayList<String> arrList = new ArrayList<String>();
        for(Node n: linkedList) {
            arrList.add(n.a);
        }
        return arrList;
    }
    
    private static class Node {
        String a;
        String b;
    }