Frage

I have this case where I am filtering list into multiple lists based on criteria.

for(SomeObj someObj : someObjs) {
    if(StringUtils.equalsIgnoreCase(someObj.getIndicator(), "Y")) {
        beansWithY.add(someObj);
    } else if(StringUtils.equalsIgnoreCase(someObj.getIndicator(), "N")) {
        beansWithN.add(someObj);
    } else {
        beansWithIndNotValid.add(someObj);
    }
}

This looks simple enough, but, I am wondering if this is possible using Lambdaj.

I came across grouping and it can be used like the following, but, it doesn't seem to cover the default scenario.

Group<SomeObj> group = group(listOfSomeObjs, by(on(SomeObj.class).getIndicator())); 

After this the result will be the following:

Y group
N group
null group
a group for each and every invalid indicator ( like A, B, C...)

I am wondering if this can be made to work like the for loop mentioned above, if it is Y - go to a list/group, N - go to another list/group, everything else to one group.

War es hilfreich?

Lösung

You can't achieve this using "group" function. The group method you added in the question is the right way to approach what you need but you won't be able to cover the default case.

If you want to use LambdaJ to do what you want you have to combine filter (or select). Here you have the code for filter:

List<SomeObj> yList = filter(having(on(SomeObj.class).getIndicator(), equalTo("Y")), listOfSomeObjs);
List<SomeObj> nList = filter(having(on(SomeObj.class).getIndicator(), equalTo("N")), listOfSomeObjs);
List<SomeObj> dList = filter(having(on(SomeObj.class).getIndicator(), not(equalTo("Y"))).and(having(on(SomeObj.class).getIndicator(), not(equalTo("N")))), listOfSomeObjs);

Map<String, List<SomeObj>> map = new HashMap<>();
map.put("Y", yList);
map.put("N", nList);
map.put("D", dList);

Hope to help.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top