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:
- Are these ANY close to being a correct, nice, following-good-practices solution?
- Is this good use for lambda? Any idea how to make it even simpler?
- 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.
(MyEnum.STATUS == object.getStatus) ? otherList : someOtherListmight be the simplest approach.