首页 > 解决方案 > 搜索地图的最佳方式

问题描述

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

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

提前致谢

标签: javalistsearchoptimizationhashmap

解决方案


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

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

推荐阅读