我有一个包含Company对象的列表。
List<Company> companiesList
而且每个公司都有一个返回公司名称的getName()
方法。
List<Company> companiesList
中有几家公司,我想将此列表与包含公司名称的字符串列表进行比较
这是我的比较清单
List<String> searchList = Arrays.asList("abc", "xyz");
我有我的方法来获取公司和流,并用DB中的一些条件对其进行过滤,我想添加另一个过滤器,它将返回与searchList中的字符串相等的公司
因此,基本上是将companiesList中的每个元素与getName()进行比较,并检查searchList列表中是否存在该元素
public List<Company> getCompanies(String country, List<String> searchList, String version) {
List<Company> result = countriesByCountryCache.getUnchecked(country)
.stream()
.filter(s -> version.compareTo(s.getVersion()) >= 0)
//here to filter like for each element, i want to compare element.getName() and check if it exists in searchList and collect it
.collect(Collectors.toList());
return result;
}
我知道这个问题已经被问了很多次,有很多例子,但我找不到一个合适的、正确的解决方案。提前感谢!
发布于 2020-05-10 06:45:11
您只需在.filter()
中添加另一个条件,以便在过滤版本后仅返回searchList
中存在的结果。
将searchList
转换为HashSet会稍微好一点,因为这样会降低从O(n)
到O(1)
搜索公司的复杂性,而且还会删除可能存在的任何重复值。传入HashSet而不是list会更好(如果您可以控制界面设计)。
这是一个代码片段,我首先将searchList
转换为一个集合,然后在.filter()
中添加一个新条件,以便只返回searchList
中存在的公司。
public List<Company> getCompanies(String country, List<String> searchList, String version) {
// Convert the given search list to a set
final Set<String> searchQueries = new HashSet<>(searchList);
List<Company> result = countriesByCountryCache.getUnchecked(country)
.stream()
.filter(s -> version.compareTo(s.getVersion()) >= 0 && searchQueries.contains(s.getName()))
.collect(Collectors.toList());
return result;
}
发布于 2020-05-10 06:44:58
public List<Company> getCompanies(String country, List<String> searchList, String version) {
List<Company> result = countriesByCountryCache.getUnchecked(country)
.stream()
.filter(s -> version.compareTo(s.getVersion()) >= 0 && searchList.contains(s.getName())
.collect(Collectors.toList());
return result;
}
请检查上面的代码是否正常工作。
发布于 2020-05-10 06:46:03
添加过滤器/编辑流中的现有过滤器,这基本上是在每次迭代时在searchList中查找countryName的存在。
List<Company> result =
countriesByCountryCache.getUnchecked(country)
.stream()
//your filters...
.filter(s -> searchList.contains(s.getName())
.collect(Collectors.toList());
return result;
https://stackoverflow.com/questions/61704637
复制相似问题