所以我的哈希映射定义为:hashmap<String,LinkedList<node>>
。
节点类包含两个字段a和b。
我有很多字符串值需要我提供信息。 我想要做的是浏览hashmap并查找与我所拥有的每个值相关联的Linkedlists,并将字段'a'的列表变为二维数组。
所以字符串值“animal”的所有'a'字段都是2d数组中的第一个数组。字符串中的所有“a”字段值“人类”都在第二个数组中,依此类推。
我知道这种情况很糟糕,但我希望你明白这一点。
答案 0 :(得分:0)
你应该考虑使用List列表而不是2D数组,因为我确定行和列非常好,你可能不知道每个的初始大小。
我做了一些假设,因为你没有指定。您可以根据需要进行修改,以适合您的特定方案。见下面的假设。
假设
hashMap
。a
类中的字段Node
属于String
实施
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;
}