1

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.

1
  • A ternary expression (MyEnum.STATUS == object.getStatus) ? otherList : someOtherList might be the simplest approach. Commented Nov 30, 2016 at 20:54

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Where is partitioningBy() defined? Is that a static import?
Static import from java.util.stream.Collectors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.