【问题标题】:Howto check if a TreeMap contains a specific object?如何检查 TreeMap 是否包含特定对象?
【发布时间】:2015-03-15 03:59:53
【问题描述】:

在一个应用程序中,我有这个 TreeMap 对象:

treePath = new TreeMap<String, DLFolder>();

第一个String参数应该是key,DLFolder是value。

好的,DLFolder 对象有这个方法 dlFolder.getPath(),它返回一个 String

所以我想知道 treePath 对象是否包含具有特定 path 值的 DLFolder 对象

我可以这样做吗?

Tnx

【问题讨论】:

  • 只是treePath.containsKey(folder.getPath()) 假设这是关键?

标签: java dictionary collections hashmap treemap


【解决方案1】:

在 Java 8 中,这相当简单。

treePath.values().anyMatch(dlf -> dlf.getPath().equals(specificValue))

【讨论】:

    【解决方案2】:

    你可以遍历TreeMap的值:

    for (DLFoder folder : treePath.values())
        if (folder.getPath().equals(somePathValue))
            // path found!
    

    【讨论】:

      【解决方案3】:
      for (DLFolder dlf : treePath.values()) {
      if ("A SPECIFIC PATH".equals(dlf.getPath()) {
      // do someting with the dlf
      }
      

      【讨论】:

        【解决方案4】:

        如果地图的键也是dlFolder.getPath()中存储的值,那么是的,你可以调用treePath.contains("Value");

        其他选项包括:

        1. 使用迭代器、增强的 for 循环或 Java 8 流对 treePath 的值进行迭代。

        2. 创建另一个映射以映射相同的DLFolder 对象,但按路径。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-07-04
          • 2012-10-17
          • 2019-01-12
          • 1970-01-01
          • 1970-01-01
          • 2022-11-09
          • 2013-04-22
          • 2020-05-24
          相关资源
          最近更新 更多