【问题标题】:How to get a subset of entries in a treemap?如何在树形图中获取条目的子集?
【发布时间】:2012-09-06 07:07:56
【问题描述】:

我有一个

TreeMap map = new TreeMap();

根据选择标准将文档中的值存储在视图中。 map 将创建日期存储为键,将文档值存储为对象。

在对象中,我有一个“表单”字段。文件可以有不同的形式(备忘录、通知、传真等)

我有一个返回 allEntries 的方法。没关系,可以按预期工作。

我现在想在表单字段上进行选择以仅返回地图中文档的子集。

有人能指出我正确的方向吗?

【问题讨论】:

    标签: java xpages


    【解决方案1】:

    由于您要在不是地图键的内容上进行选择,因此您必须遍历所有项目。

    如果您可以使用外部库,则可以使用来自 google 的 guava librariesCollections2.filter()。即。

    TreeMap<Date, Document> map = ...;
    final String formValue = "notice";
    Collection<Document> result = Collections2.filter(map.values(), new Predicate<Document>() {
        public boolean apply(Document input) {
            return formValue .equals(input.getForm());
        }
    }
    

    【讨论】:

    【解决方案2】:

    您可以使用 2 个地图来存储数据。

    一个简单的 Hashmap 足以存储与备忘录通知等对应的 id,并作为值存储包含当前格式的所有相应数据的 Treemap。

    【讨论】:

      【解决方案3】:

      你可以 1)遍历所有值并将这些匹配条件放入新集合中 2)将它存储在其他集合(单独的变量或 Map> (或类似的东西,考虑使用 set 而不是 List)

      1) 较慢的检索,2) 较慢的删除,更多的内存消耗

      【讨论】:

        【解决方案4】:

        guava 库可以工作,但有点矫枉过正。所以我最终得到了以下内容

        TreeMap<String, Object> mapFiltered = new TreeMap<String, Object>();
        LinkedList<CommunicationDocumentEntry> map = new LinkedList<CommunicationDocumentEntry>();
        
            public Collection<Object> getAllEntries(String frm, boolean order) {
            this.mapFiltered.clear();
        
            Iterator<CommunicationDocumentEntry> itr = this.map.iterator();
            while (itr.hasNext()) {
                CommunicationDocumentEntry entry = itr.next();
                if (EMPTY_STRING.equals(frm) || frm == null) {
                    this.mapFiltered.put(entry.getDateCreated(), entry.getEntry());
                } else {
                    if (entry.getForm().toUpperCase().equals(frm.toUpperCase())) {
                        this.mapFiltered.put(entry.getDateCreated(), entry.getEntry());
                    }
                }
            }
        
            if (order) {
                return this.mapFiltered.descendingMap().values();
            } else {
                return this.mapFiltered.values();
            }
        }
        

        当然不完美,但对我有用......

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-07
          • 2021-10-31
          • 2023-04-01
          • 2011-09-15
          • 1970-01-01
          相关资源
          最近更新 更多