【问题标题】:Convert lists in hashmap to a 2d array将 hashmap 中的列表转换为二维数组
【发布时间】:2016-01-18 04:01:22
【问题描述】:

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

我有许多需要信息的字符串值。 我想要做的是遍历哈希图并查找与我拥有的每个值关联的链接列表,并将字段“a”的列表放入二维数组中。

所以字符串值“animal”的所有“a”字段都将成为二维数组中的第一个数组。字符串值“humans”的所有“a”字段都在第二个数组中,依此类推。

我知道这有点乱,但我希望你明白这一点。

【问题讨论】:

    标签: java arrays linked-list hashmap


    【解决方案1】:

    您应该考虑使用列表列表而不是 2D 数组,因为我确信行和列会非常好,您可能无法提前知道每个的初始大小。

    由于您没有具体说明,我做了一些假设。您可以根据需要进行修改以适用于您的特定场景。见下面的假设。

    假设

    1. 您关心的“字符串”,即“动物”、“人类”是您 hashMap 的键。
    2. Node 类中的字段a 的类型为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;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-17
      • 2022-01-15
      • 2011-12-04
      • 2016-09-24
      • 2014-10-13
      • 2015-11-20
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多