简体   繁体   中英

Joining two lists in java

I have lists of different classes, say A and B respectively. Definition of these classes is as follows-

class A {
 int field1;
 int field2;
}

class B {
 int field1;
 int field3;
}

class C {
 int field1;
 int field2;
 int field3;
}

I want to perform a join operation (similar to database join) on A and B, over field1 and populate the result in C.

I can iterate over the lists and do it. But, just wanted to check whether there are any library methods which does similar sort of thing.

If these are the only fields you're using, just iterate manually.

For larger data sets, group your data into Collections and apply a Cartesian Product algorithm .

You can add objects of any class to the list(if your list is not generic-specified). But when you get each object back from the list, you will not know the object is of which type.

Maybe by using a method in library in apache collections:

import org.apache.commons.collections.ListUtils;    

List<?> newListC = ListUtils.intersection(list1, list2);

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM