2015-10-19 117 views
0

所以我將hashmap定義爲:hashmap<String,LinkedList<node>>。 節點類包含兩個字段a和b。將hashmap中的列表轉換爲2d數組

我有一些我需要信息的字符串值。 我想要做的是通過哈希映射,並查找與我已經獲得的每個值關聯的Linkedlists,並將字段'a'的列表獲取到2d數組中。

因此,字符串值「animal」的所有'a'字段將成爲2d數組中的第一個數組。字符串值「人類」的所有'a'字段位於第二個數組中,等等。

我知道它一塌糊塗,但我希望你明白這一點。

回答

0

您應該考慮使用列表列表而不是2D數組,因爲我確定行和列將非常精確,而且您可能不會提前知道每個列的初始大小。

我做了一些假設,因爲你沒有指定。您可以根據需要進行修改以適用於您的特定場景。見下面的假設。

假設

  1. 的 「琴絃」 你在乎即 「動物」, 「人」 是你hashMap的鑰匙。
  2. 領域aNode類類型的String
  3. 你關心

實現你有一個列表中的所有字符串

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