我有两个POJO类,每个类都有一个唯一ID的不同字段。
我想要对两个List<A>
和List<B>
进行交集操作。
最好的方法是什么?一种方法是简单地迭代两次,但复杂度太高,为n2。
是否有更好的办法?我能用比较器做到吗?
Class A {
Id, Name ,DOB}
Class B{
id, aid ,location }
我有一个A列表和一个B列表
现在想要获取A列表中在B列表中的位置
Apache Commons Collections有一个方法可以做到这一点:CollectionUtils.intersection。 但是它不使用泛型。
此外,还有这个SO问题:List intersection in java
使用Java 8流
List<A> listA = new ArrayList<A>();
List<B> listB = new ArrayList<B>();
Set<Integer> aIdsFromBList = listB.stream().map(B::getAId).collect(Collectors.toSet());
return listA.stream
.filter(a -> aIdsFromBList.contains(a.getId()))
.collect(Collectors.toList());
List<B>
元素放入一个HashMap<Integer,B>
中,其中id
是键。List<A>
的元素,并使用哈希映射快速查找相应的B
元素。这将提供所需的结构("在B
中位置的A
列表")。Set
而不是 Map
(你只是在使用 map 的 keyset - 这听起来很熟悉.. keySET?... SET?) 天啊... - BohemianMap
仍然是错误的工具。 - Bohemian按Id递增的顺序对列表进行排序。
从List A开始,在List B中找到相应的索引。记住List B的当前索引,称为(indB)
从List A的下一个索引开始,并从(indB+1)开始在List B中比较。
重复步骤1-4,直到List A或List B结束为止。
试试这个:
public static void main(String[] args) {System.nanoTime()
List<A> as = new ArrayList<A>();
List<B> bs = new ArrayList<B>();
// Collect all A.ids in the list of B into a Set
Set<String> baids = new HashSet<String>();
for (B b : bs)
baids.add(b.aid);
// iterate through the list of A discarding those that don't have a B
for (Iterator<A> i = as.iterator(); i.hasNext();)
if (!baids.contains(i.next().Id)) // contains() executes fast for a Set
i.remove();
// now list "as" contains all A that have a B with A.Id = B.aid
}
main()
的最后一行可能甚至无法编译。即使它能够编译,你已经失去了 A
的所有属性。坦白地说,我认为这场辩论对我们两个人来说都是浪费时间。我们显然没有达成共识。 - NPE
Set
和List
并不完全相同。 - Paulnew HashSet<?>(list)
就可以了。 - Bohemian