you've got several issues with your code i.e:
postCodes.addAll
is a side-effect and therefore you should avoid doing that otherwise when the code is executed in parallel you'll receive non-deterministic results.
flatMap
expects a stream, not a boolean; which is what your code currently attempts to pass to flatMap
.
flatMap
in this case consumes a function that also consumes a value and returns a value back and considering you've decide to use a lambda statement block then you must include a return statement within the lambda statement block specifying the value to return. this is not the case within your code.
- stream pipelines are driven by terminal operations which are operations that turn a stream into a non-stream value and your code currently will not execute at all as you've just set up the ingredients but not actually asked for a result from the stream.
- the receiver type of your query should be
List<String>
not List<Entry>
as within your current code the call to Arrays.asList(properties.getPostcodes().split(","))
returns a List<String>
which you then add to an accumulator with the call addAll
.
- thanks to Holger for pointing it out, you're constantly failing to decide whether the variable is named
entry
or recordEntry
.
That said here's how I'd rewrite your code:
List<String> entries = x.getEntry.stream()
.filter(Objects::nonNull)
.map(Entry::getContent)
.map(Content::getProperties)
.map(Properties::getPostcodes)
.flatMap(Pattern.compile(",")::splitAsStream)
.collect(Collectors.toList());
and you may want to use Collectors.toCollection
to specify a specific implementation of the list returned if deemed appropriate.
edit:
with a couple of good suggestions from shmosel we can actually use method references throughout the stream pipelines and therefore enabling better intent of the code and a lot easier to follow.
or you could proceed with the approach:
List<String> entries = x.getEntry.stream()
.filter(e -> e != null)
.flatMap(e -> Arrays.asList(
e.getContent().getProperties().getPostcodes().split(",")).stream()
)
.collect(Collectors.toList());
if it's more comfortable to you.