【问题标题】:Most optimal way to search through a Map搜索地图的最佳方式
【发布时间】:2018-11-20 04:59:10
【问题描述】:

我有一张像这样的地图(比如说人):

public Map<String, Person> personMap = new HashMap<>();

我想通过这个按名称过滤的地图进行搜索。 我有这段代码,但我很好奇是否有更优化或更优雅的方法来做到这一点。

public ArrayList<Person> searchByName(String query) {
    ArrayList<Person> listOfPeople = new ArrayList<>();
    for (Map.Entry<String, Person> entry : this.personMap.entrySet()) {
        Person person = entry.getValue();
        String name = entry.getValue().getName();
        if (name.toLowerCase().contains(query.toLowerCase())) {
            listOfPeople.add(person);
        }
    }
    if (listOfPeople.isEmpty()) {
        throw new IllegalStateException("This data doesn't appear on the Map");
    }
    return listOfPeople;
}

提前致谢

【问题讨论】:

  • 如果没有按名称键入,那么迭代是搜索每个条目的唯一方法。然而,为非异常状态抛出异常可能不是处理失败搜索的最佳方法。不找到您正在寻找的东西并不罕见 - 只需返回一个空列表并通过正常流程处理该案例。
  • 地图中的第一个参数String是什么?名字?因为您没有在for 中使用它。
  • 毫无疑问,有人会建议基于流的解决方案。你可以这样得到 terser,也许你会认为这样更优雅。我自己,我观察到由于您对此目的根本对密钥不感兴趣,因此通过条目集解决问题有点浪费。为什么不直接使用 values() 集合呢?
  • OP 返回People 列表的事实表明他们key 不是必需的条目
  • Optional 比异常好。

标签: java list search optimization hashmap


【解决方案1】:

考虑了一下,似乎将提供基于流的解决方案。我不是那种“现在就用流做所有事情”的人,但是流确实提供了一种相当简单易读的方式来表达某些类型的计算,而你的就是其中之一。结合我的观察,你应该直接使用地图的值集合,你会得到:

listOfPeople = personMap.values().stream()
        .filter(p -> p.getName().contains(query.toLowerCase()))
        .collect(Collectors.toList());
if (listOfPeople.isEmpty()) {
    // ...

【讨论】:

    【解决方案2】:

    您可以使用 java Stream API。

    personMap.entrySet().stream()
        .filter(entry -> entry.getValue().getName().toLowerCase().contains(query.toLowerCase())
        .map(entry -> entry.getValue())
        .collect(Collectors.toList());
    

    【讨论】:

      【解决方案3】:

      我认为您的解决方案接近最优(使用 Streams 除外)。我会将for 子句简化为:

      for (Person person : this.personMap.values()) {
          String name = person.getName();
          if (name.toLowerCase().contains(query.toLowerCase())) {
              listOfPeople.add(person);
          }
      }
      

      因为你根本没有使用地图的键。

      【讨论】:

        猜你喜欢
        • 2010-10-12
        • 2011-06-18
        • 2014-12-27
        • 2021-07-31
        • 2010-10-17
        • 2010-11-26
        • 2019-07-12
        • 2013-03-13
        • 1970-01-01
        相关资源
        最近更新 更多