繁体   English   中英

在Java中创建多维HashMap

[英]Create Multidimensional HashMap in java

我是Java的新手,我有这段代码

...
NodeList indexEntryList = sourceDoc.getElementsByTagName("in.ar");  //this is a xml tag
for (int i = 0; i < indexEntryList.getLength(); i++) {
    ...
}
...

我必须创建一个HashMap(或类似的东西),在其中保存作为节点属性的字符串和具有相同属性的所有节点的列表。

我认为是这样的:

Map<String, ArrayList<Node>> indexCategories = new HashMap<String, ArrayList<Node>>();

但是在每次的for中,我都不知道如何在Map的所有键中进行搜索,并将新Node添加到列表中,如果该键尚不存在,请在Map内创建新项。

使用Map#containsKey()搜索是否存在密钥,使用Map#get()获取集合(如果存在)各自的Map#put()来存储新创建的地图。 顺便说一句,所有内容都可以正确地记录在Map API中。

试试这个...

 Map<String, ArrayList<Node>> indexCategories = new HashMap<String, ArrayList<Node>>();

 public void addNode(string key, Node node) {
     List<Node> nodes;

     if(indexCategories.containsKey(key)) {
        nodes = indexCategories.get(key);
     } 
     else {
        nodes = new ArrayList<Node>();
     }

     nodes.add(node);

     indexCategories.put(key, node);
 }

您可以使用类似:

    String key = nodeAttribute;
    if (!indexCategories.containsKey(key)) {
        indexCategories.put(key, new ArrayList<Node>());
    }
    indexCategories.get(key).add(node);

如果查看NodeList的文档,将会看到它只有两种方法: getLength() (您已使用过)和Node item(int index)

因此,您的循环将是:

for (int i = 0; i < indexEntryList.getLength(); i++) {
    Node node = indexEntryList.item(i);
    // do something with node
}

...以及您要对节点执行的操作就是找到其属性。

 NamedNodeMap attributes = node.getAttributes();
 if(attributes != null) {
       for(int j=0;j < attributes.getLength(); j++) {
           Node attribute = attributes.item(j);
           // do something with node and attribute
       }
 }

...那么您想对属性及其节点做什么? 我不确定,但我您的意图是map.get(attributeName)返回包含该元素的节点列表。

如果是这样的话:

  // get the list for this element, or create one
  List list = map.get(attribute.getName());
  if(list == null) {
     list = new ArrayList();
     map.put(attribute.getName(), list);
  }
  // add the node we're working with to that list
  list.add(node);

这里有几点注意事项:

  • 使用Set可能比使用List更好,因为最终可能会将同一节点多次添加到List。
  • 我真的建议将这些块中的每个块放入一个单独的方法中,彼此调用一个方法-也就是说,在我已do something... ,进行方法调用。 这样可以使您的代码块更小巧,更易于理解和测试。 这也意味着您可以在两个“ for”循环中将循环计数器称为“ i”。

你可能会尝试这样的事情

    NodeList indexEntryList = sourceDoc.getElementsByTagName("in.ar");  //this is a xml tag
    for (int i = 0; i < indexEntryList.getLength(); i++) {
         Node oneItem = indexEntryList.item(i);
         String someString = "xxx or however you obtain the string";
         ArrayList<Node> listOfNodes = indexCategories.get(someString);
         if (listOfNodes == null) {
             listOfNodes = new ArrayList<Node>();
         }
         listOfNodes.add(oneItem);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM