I've a List of Foo, where on each Foo I apply a processor method to get ValidItem
.
If there is an error in processing, then I returned ErrorItem
.
Now How to process this by Java 8 streams to get the result in form of 2 different lists
List<Foo> FooList = someList....;
class ValidItem extend Item{......}
class ErrorItem extend Item{......}
Item processItem(Foo foo){
return either an object of ValidItem or ErrorItem;
}
I believe I can do this
Map<Class,List<Item>> itemsMap =
FooList
.stream()
.map(processItem)
.collect(Collectors.groupingBy(Object::getClass));
But as List<Parent>
IS NOT a List<Child>
so I can't typecast the map result into List<ValidItem>
In reality ErrorItem
and ValidItem
are two completely different class not related at all, just for the sake of this steam processing and processItem method I kept them in same hierarchy by extending a marker Item class,.
and in many other Places in code, I cant/shouldn't refer ValidItem as Item , as It give an idea that it can be an ErroItem too.
Is there a proper way of doing it with streams, where at the end I get 2 lists. and ErrorItem and ValidItem are not extending same Item class ?
############## Update ##############
As I said ValidItem and ErrorItem shouldn't be same, so I changed the signature of process method and passed it a list.
I know this is not how Stream shold be used. Let me know if you have better way
List<Foo> FooList = someList....;
class ValidItem {......}
class InvalidFoo{......}
ValidItem processFoo(Foo foo, List<InvalidFoo> foolist){
Do some processing on foo.
either return new ValidItem ();
OR
fooList.add(new InvalidFoo()) , and then return null;
}
List<InvalidFoo> invalidFooList = new ArrayList();
List<ValidItem> validItem =
fooList
.stream()
.map(e->processItem(e,invalidFooList))
.filter(Objects::notNull)
.collect(Collectors.toList());
now I have both invalid and valid list, but this doesn't look like a clean stream code.