【问题标题】:Java Mapping ArrayList to HashMapJava 将 ArrayList 映射到 HashMap
【发布时间】:2011-04-18 01:07:19
【问题描述】:

我的页面获得了一个 ArrayList,其中每个文档都有一个名为 type 的属性。

我不知道唯一类型或文档的数量。

我想将此 ArrayList 排序为 HashMap,但我无法理解它。

一些伪代码喜欢

for (int i = 0; i < documents.size(); i++) 
{
   if there is an array for documents[i].type
   add to this array
   else create a new array for this type
   add document[i].type and the array of documents with matching type to the hashmap
}

我知道这是错误的方法,显然行不通。我愿意接受任何建议。

谢谢

【问题讨论】:

    标签: java sorting arraylist hashmap


    【解决方案1】:

    我认为您要查找的术语不是按类型排序,而是按类型索引GuavaMultimap 接口旨在将键映射到多个值,而无需处理值集合的所有麻烦。特别是,Guava 有一种方法可以完全按照您的要求进行:

    List<Document> documents = ...
    ImmutableListMultimap<Type, Document> typeIndex = Multimaps.index(documents,
        new Function<Document, Type>() {
          public Type apply(Document input) {
            return input.getType();
          }
        });
    
    for(Type type : typeIndex.keySet()) {
      ImmutableList<Document> documentsWithType = typeIndex.get(type);
      ...
    }
    

    这和做的差不多:

    ListMultimap<Type, Document> typeIndex = ArrayListMultimap.create();
    for(Document document : documents) {
      typeIndex.put(document.getType(), document);
    }
    

    除了生成的多图是不可变的。另请注意,以上内容几乎完全等同于 Mark 的示例。

    【讨论】:

      【解决方案2】:
      // create the map to store stuff, note I'm using a List instead of an array
      // in my opinion it's a bit cleaner
      Map<String, List<Document>> map = new HashMap<String, List<Document>>();
      
      // now iterate through each document
      for(Document d : documents){
      
          // check to see if this type is already known
          List<Document> list = map.get(d.type);
      
          if(list == null){
              // list is null when it wasn't found in the map
              // this is a new type, create a new list
              list = new ArrayList<Document>();
      
              // store the list in the map
              map.put(d.type, list);
          }
      
          // finally, whether we got a hit or a miss, we want
          // to add this document to the list for this type
          list.add(d);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-13
        • 2014-06-14
        • 2020-10-22
        • 2021-11-05
        • 1970-01-01
        • 1970-01-01
        • 2014-08-04
        • 2016-07-02
        相关资源
        最近更新 更多