Bobzone
Bobzone

Reputation: 286

Lambda usage to eliminate if

trying to learn something new about practical lambda usages.

I have this problem:

I have an object that has a List of certain other objects inside. Those objects have MyEnum field. I want to iterate through those objects, get the state of that Enum and then according to that I want to add the object to List1, if a condition is met. If it is not, I want to add the object to List2.

Basically splitting a list to two different lists with a special condition.

I have worked my way through two methods to achieve that, one being an archaic, classical for-each, second being java 8 lambdas, that I'm trying to learn as well.

My codes for both:

void groupObjects() {

    for (ListObject listObject : object.getList()) {
        if (MyEnum.STATUS.equals(listObject.getStatus())) {
            otherList.add(listObject);
        } else {
            someOtherList.add(listObject);
        }
    }
}


void groupObjects() {

    object.getList().parallelStream()
            .filter(listObject-> MyEnum.STATUS.equals(listObject.getStatus()))
            .forEach(listObject-> otherList.add(listObject));
    object.getList().parallelStream()
            .filter(listObject-> !MyEnum.STATUS.equals(listObject.getStatus()))
            .forEach(listObject-> someOtherList.add(listObject));
}

And questions that raised in my head:

  1. Are these ANY close to being a correct, nice, following-good-practices solution?
  2. Is this good use for lambda? Any idea how to make it even simpler?
  3. Maybe I should consider other classes or methods for this task?

I read already about the .parallelStream() part, so don't mind that for now.

Upvotes: 1

Views: 88

Answers (1)

Simon
Simon

Reputation: 6363

This can be achieved by using partitioningBy

Map<Boolean, List<SomeClass>> partitioned = object.getList().stream()
    .collect(partitioningBy(listObject->MyEnum.STATUS.equals(listObject.getStatus()))

Where partitioned.get(true) will give you a list with the objects that had the status MyEnum.STATUS and partitioned.get(false) will get you the objects that didn't.

Upvotes: 3

Related Questions