I have a list of elements. I want to group the elements of this list into a list of list based on some condition. Is it possible to do it easily in java ?
public class CollectionTest {
public static void main(String[] arg) {
Target target0 = new Target();
target0.setRisklevel("III");
target0.setLocation("Combined");
Target target1 = new Target();
target1.setRisklevel("III");
target1.setLocation("Combined");
Target target2 = new Target();
target2.setRisklevel("III");
target2.setLocation("Combined");
Target target3 = new Target();
target3.setRisklevel("III");
target3.setLocation("Combined");
Target target4 = new Target();
target4.setRisklevel("IV");
target4.setLocation("Combined");
Target target5 = new Target();
target5.setRisklevel("IV");
target5.setLocation("Combined");
Target target6 = new Target();
target6.setRisklevel("IV");
target6.setLocation("Combined");
Target target7 = new Target();
target7.setRisklevel("II");
target7.setLocation("Domestic");
Target target8 = new Target();
target8.setRisklevel("IV");
target8.setLocation("Domestic");
Target target9 = new Target();
target9.setRisklevel("IV");
target9.setLocation("Domestic");
Target target10 = new Target();
target10.setRisklevel("IV");
target10.setLocation("Domestic");
Target target11 = new Target();
target11.setRisklevel("IV");
target11.setLocation("Domestic");
List<Target> ucrtargetList = new ArrayList<Target>();
ucrtargetList.add(target0);
ucrtargetList.add(target1);
ucrtargetList.add(target2);
ucrtargetList.add(target3);
ucrtargetList.add(target4);
ucrtargetList.add(target5);
ucrtargetList.add(target6);
ucrtargetList.add(target7);
ucrtargetList.add(target8);
ucrtargetList.add(target9);
ucrtargetList.add(target10);
ucrtargetList.add(target11);
List<List<Target>> fullList = new ArrayList<List<Target>>();
}
}
Here condition is RiskLevel and Location has to be same in each list in the list of List. So fullList should have 4 lists within it(1st III & Combined, 2nd IV & Combined, 3rd II & Domestic, 4th IV & Domestic).
I could loop through the list and set the values. Is there an easier way to do this with java8 or apache commons ?