我有一个像这样的 map (比如说人,每个例子):
public Map<String, Person> personMap = new HashMap<>();
我想通过名称过滤这张 map 进行搜索。 我有这段代码,但我很好奇是否有更优化或更优雅的方法。
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;
}
提前致谢
最佳答案
考虑片刻后,我似乎是要提供基于流的解决方案的人。我不是那种“现在用流做所有事情”的人,但流确实提供了一种相当简单易读的方式来表达某些类型的计算,而你的就是其中之一。结合我的观察,您应该直接使用 map 的值集合,您会得到:
listOfPeople = personMap.values().stream()
.filter(p -> p.getName().contains(query.toLowerCase()))
.collect(Collectors.toList());
if (listOfPeople.isEmpty()) {
// ...
关于java - 搜索 map 的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50789322/