如何从集合对象集合中检索用户定义的对象

时间:2016-08-14 15:59:52

标签: java

在我的一个要求中,我有一个密钥,每个密钥与多个文档对象相关联             这些我用密钥和值对存储到HashMap中.Key是id,值是List of             与该kEY相关的文件

        Ex : HashMap<String,List<Document>> 

        I want to put all the list documents in one collection object , ie.List<Documents> (all documents of all keys)
        When i am using values() method of Hashmap i am getting Collection<List<Document>>

        If i want to get all the document objects i have to get each List<Document> ,iterate and add it into new collection object.

        other than this Is there any best way i can get all the Documents one at a time in collection Object.
        using any apache common-collections or apache commons-collections4 api ?


        ArrayList<Document> al = new ArrayList<Document>();
        Document dto1 = new Document();
        dto1.setResearchId("1");
        dto1.setIsinCode("isinCode1");
        dto1.setEquity("equity1");

        Document dto2 = new Document();
        dto2.setResearchId("2");
        dto2.setIsinCode("isinCode2");
        dto2.setEquity("equity2");

        Document dto3 = new Document();
        dto3.setResearchId("3");
        dto3.setIsinCode("isinCode3");
        dto3.setEquity("equity3");

        Document dto4 = new Document();
        dto4.setResearchId("4");
        dto4.setIsinCode("isinCode4");
        dto4.setEquity("equity4");

        al.add(dto1);
        al.add(dto2);
        al.add(dto3);
        al.add(dto4);

        Map<String ,List<Document>> mapList = 
                 new HashMap<String,List<Document>>();
        mapList.put("1", al);
        mapList.put("2", al);
        mapList.put("3", al);


      Excepted output : Collection<Document>

       For sample i have added the same arraylist object in to my Map 
       but in actual i will have different arrayList objects.

2 个答案:

答案 0 :(得分:1)

您似乎正在尝试将List的值中的Map展平为单个集合。 Java 8允许您非常轻松地执行此操作:

List<Document> flatDocuments = // could also be defined as a Collection<Document>
    mapList.values()
           .stream()
           .flatMap(Collection::stream)
           .collect(Collectors.toList());

或者,如果您只想对它们执行某些操作(例如打印它们),则可以跳过收集阶段并使用forEach直接对其进行操作:

mapList.values()
       .stream()
       .flatMap(Collection::stream)
       .forEach(System.out::println);

修改:
对于较旧的Java版本,您必须使用循环自己实现相同的逻辑(或者,当然,使用为您执行此操作的第三方):

List<Document> flatDocuments = new LinkedList<>();
for (List<Document> list : mapList.values()) {
    flatDocuments.addAll(list);
}

答案 1 :(得分:0)

既然你自己建议apache commons-collections4,你真的看过吗?

http://localhost:27855/ScriptResource.axd?d=values()方法完全符合您的要求。

  

<强> Collection<V> values()

     

获取此多值地图中包含的所有值的Collection视图。

     

实现通常会返回一个包含所有键值组合的集合。