用Java中的流比较两个List元素并返回。

问题描述 投票:0回答:1

我有一个包含公司对象的列表。

List<Company> companiesList

而每个公司都有一个 getName() 方法,返回公司名称。

List<Company> companiesList 里面有几个公司,我想把这个列表和一个包含公司名称的字符串列表进行比较。

这是我的比较清单

List<String> searchList = Arrays.asList("abc", "xyz");

我有一个方法可以从DB中获取公司和数据流,并通过一些条件进行过滤,我想添加另一个过滤器,返回与searchList中的字符串相同的公司。

所以基本上,我们的想法是用getName()来比较companiesList中的每个元素,并检查该元素是否存在于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;
}

我知道这个问题已经问过很多次了,也有很多例子,但我找不到合适的、正确的解决方法。先谢谢你

java list filter stream compare
1个回答
3
投票

你可以在你的 .filter() 只返回存在于您的 searchList 一旦你筛选出版本。

的时候,将其转换为 searchList 到一个HashSet,因为你会降低搜索公司的复杂度,从 O(n)O(1) 并且它还会负责删除你可能有的任何重复的值。传入HashSet而不是列表更好(如果你能控制界面设计的话)。

这里是我首先转换HashSet的一个片段。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;
}

3
投票
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;
}

请检查以上代码是否有效。


1
投票

在你的流中添加一个过滤器,它基本上是在每次迭代时寻找 searchList 中的 countryName 的存在。

   List<Company> result = 
       countriesByCountryCache.getUnchecked(country)
            .stream()
            //your filters...
            .filter(s -> searchList.contains(s.getName())
            .collect(Collectors.toList());
            return result;
© www.soinside.com 2019 - 2024. All rights reserved.