Java将ArrayList映射到HashMap - java

我给页面提供了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参考方案

// 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);
}

java:继承 - java

有哪些替代继承的方法? java大神给出的解决方案 有效的Java:偏重于继承而不是继承。 (这实际上也来自“四人帮”)。他提出的理由是,如果扩展类未明确设计为继承,则继承会引起很多不正常的副作用。例如,对super.someMethod()的任何调用都可以引导您通过未知代码的意外路径。取而代之的是,持有对本来应该扩展的类的引用,然后委托给它。这是与Eric…

Java-如何将此字符串转换为日期? - java

我从服务器收到此消息,我不明白T和Z的含义,2012-08-24T09:59:59Z将此字符串转换为Date对象的正确SimpleDateFormat模式是什么? java大神给出的解决方案 这是ISO 8601标准。您可以使用SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM…

从方法返回数组-Java - java

private static Coordinate[] getCircleCoordintaes() { Coordinate coordinates[] = {new Coordinate(0, 0)}; return coordinates; } 以上程序工作正常。在上面的程序中,返回的坐标数组首先初始化了数组使用这条线Coordinate coordi…

Java Swing SearchBox模型 - java

我需要使用Java Swing的搜索框,如果单击任何建议,当输入字母时它将显示来自数据库的建议,它将执行一些操作。如果有可能在Java swing中,请提供源代码提前致谢 java大神给出的解决方案 您可以使用DefaultComboBoxModel,输出将是这样。Try this在此代码中,您将找到countries数组,因此您需要从数据库中获取此数组。

JAVA:如何检查对象数组中的所有对象是否都是子类的对象? - java

我有一个对象数组。现在,我要检查所有这些对象是否都是MyObject的实例。有没有比这更好的选择:boolean check = true; for (Object o : justAList){ if (!(o instanceof MyObject)){ check = false; break; } } java大神给出的解决方案 如果您不喜欢循环,则…