Iterating a List - General Logic
I have a list of beans ( List<AClass>
) from which I create two subdirectories based on some logic that involves validating a field from a bean class like action. if a
bean.getAction.equals("true") - add to new sublist - List<AClass> listA
else - add to new sublist - List<AClass> listB
I created a method for it and it works great.
Now I have a similar task for another bean class where I have List<BClass>
one that also has an action field and a getAction method. I want to create a generic method that will serve both of these beans (and other beans like that).
How to create such a method?
+3
source to share
3 answers
Something like this should work:
interface HasAction {
public String getAction();
}
public class AClass implements HasAction {
private final String action;
public AClass (String action) {
this.action = action;
}
@Override
public String getAction() {
return action;
}
}
public class BClass implements HasAction {
private final String action;
public BClass (String action) {
this.action = action;
}
@Override
public String getAction() {
return action;
}
}
public <T extends HasAction> List<T> subList(List<T> list) {
List<T> subList = new ArrayList<T> ();
for ( T source : list ) {
if ( source.getAction().equals("true")) {
subList.add(source);
}
}
return subList;
}
+1
source to share