java - 搜索地图的最佳方式
问题描述
我有一个像这样的地图(比如说人,例如):
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;
}
提前致谢
解决方案
想了想,似乎我是要提供基于流的解决方案的人。我不是那种“现在就用流做所有事情”的人,但流确实提供了一种相当简单易读的方式来表达某些类型的计算,而你的就是其中之一。结合我的观察,你应该直接使用地图的值集合,你会得到:
listOfPeople = personMap.values().stream()
.filter(p -> p.getName().contains(query.toLowerCase()))
.collect(Collectors.toList());
if (listOfPeople.isEmpty()) {
// ...
推荐阅读
- r - 如何在绘图的 Y 轴上的每个点上添加三个条形
- java - 如何更新三角形的坐标?
- python-3.x - 如何在 mac os x mojave 上安装 XMP Toolkit
- javascript - 如何在函数之外检索结果
- r - 在R中计算栅格堆栈中的点数
- php - 如何从文本字段中获取给定数量的加密货币的实时值
- opengl-es - glMapBufferRange 是否等待具有上下文资源共享的 glBufferSubData?
- c# - SSH 主机密钥指纹...与模式不匹配...在 C# 中使用 WinSCP .NET 程序集下载文件时
- swiftui - 是不是不能把 SwiftUI 视图放到一个框架里?
- pandas - Groupby 根据计数过滤,计算持续时间,倒数第二个状态