比较填充有不同种类对象的两个集合

Compare two Collections populated with different kinds of objects

我在尝试比较两个大集合时遇到性能问题,我正在寻求帮助以找到更好的方法。

类:

public class TypeOne {
   private int id;
}

public class TypeTwo {
   private int id;
}

代码:

Collection<TypeOne> oneColl = someMethodToPopulateThat();
Collection<TypeTwo> twoColl = anotherMethodToPopulateThat();

// Iterating both collections to match the elements by id
for(TypeOne one : oneColl) {
   for(TypeTwo two : twoColl) {
      if (one.getId().equals(two.getId())) 
         System.out.println(one.getId());
   }
}

我已经尝试使用 Stream 的一些功能 API 但我没有成功。 有没有人有解决这个问题的想法?请。

提前致谢。

tl;博士

ones.stream().forEach(
    one -> System.out.println(
        twos.stream().filter( two -> two.getId() == one.getId() ).findAny().toString()
    )
)

详情

我假设排序 NavigableSet 会提高我们搜索的性能,尽管我还没有证实这种优化尝试有效。

NavigableSet < TypeOne > ones = new TreeSet <>( Comparator.comparingInt( TypeOne :: getId ) );
ones.addAll( collectionOfOnes ) ;

NavigableSet < TypeTwo > twos = new TreeSet <>( Comparator.comparingInt( TypeTwo :: getId ) );
twos.addAll( collectionOfTwos ) ;

循环一个可导航集,同时在另一个可导航集中搜索匹配项。

for( TypeOne one : ones )
{
    Optional<TypeTwo> optionalTwo = twos.stream().filter( two -> two.getId() == one.getId() ).findAny() ;
    // handle your Optional which may or may not contain an object. 
}