搜索地图的最佳方式

jua*_*ran 2 java optimization search list hashmap

我有一个地图(比如人们,每个例子),像这样:

public Map<String, Person> personMap = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)

我想按名称搜索此地图过滤.我有这个代码,但我很好奇是否有更优化或更优雅的方式来做到这一点.

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;
}
Run Code Online (Sandbox Code Playgroud)

提前致谢

Joh*_*ger 5

考虑到这一点,认为我是那个将提供基于流的解决方案的人.我不是一个"现在用流做任何事情"的人,但是流提供了一种相当简单易读的方式来表达某种类型的计算,而你的是其中之一.结合我的观察,你应该直接使用地图的价值集,你得到这个:

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