我在尝试比较两个大集合时遇到性能问题,我正在寻求一些帮助以找到更好的方法来做到这一点。
课程:
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的一些功能,但没有成功。 有谁有解决这个问题的想法吗?请。
提前致谢。
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.
}
如果比较集合元素的属性是
int
我们可以使用 bitset api 以获得更好的性能
BitSet setOne = new BitSet();
BitSet setTwo = new BitSet();
List<TypeOne> l1 = java.util.Arrays.asList(new TypeOne(7),new TypeOne(1), new TypeOne(88));
List<TypeTwo> l2 = java.util.Arrays.asList(new TypeTwo(1), new TypeTwo(98),new TypeTwo(7));
l1.stream()
.map(t->t.id)
.forEach(setOne::set);
for (TypeTwo typeTwo : l2) {
setTwo.set(typeTwo.id);
}
setOne.and(setTwo);//find the commons in setOne
setOne.stream().forEach(i-> System.out.println(i));