Java 将hashmap中的列表转换为二维数组
所以我将hashmap定义为:hashmap。 node类包含两个字段a和b 我有许多字符串值,我需要这些值的信息。 我要做的是遍历hashmap,查找与我得到的每个值相关联的LinkedList,并将字段“a”的列表放入一个2d数组中 因此,字符串值的所有“a”字段都将成为2d数组中的第一个数组。字符串值的所有“a”字段都必须在第二个数组中,以此类推Java 将hashmap中的列表转换为二维数组,java,arrays,linked-list,hashmap,Java,Arrays,Linked List,Hashmap,所以我将hashmap定义为:hashmap。 node类包含两个字段a和b 我有许多字符串值,我需要这些值的信息。 我要做的是遍历hashmap,查找与我得到的每个值相关联的LinkedList,并将字段“a”的列表放入一个2d数组中 因此,字符串值的所有“a”字段都将成为2d数组中的第一个数组。字符串值的所有“a”字段都必须在第二个数组中,以此类推 p>我知道它是一团糟,但我希望你明白这一点。 你应该考虑使用一个列表而不是2D数组,因为我确信行和列会非常好,并且你可能不知道每一个的初始大小
<> p>我知道它是一团糟,但我希望你明白这一点。 你应该考虑使用一个列表而不是2D数组,因为我确信行和列会非常好,并且你可能不知道每一个的初始大小。 我做了一些假设,因为你没有具体说明。您可以根据需要进行修改,以适用于特定场景。见下面的假设 假设 您关心的字符串,即动物、人类是hashMap的键。 节点类中的字段类型为字符串 你有一个你关心的所有字符串的列表 实施
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;
}