2015-10-19 69 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; 
}