Thanks for sharing. Could you please provide some examples (i.e. kinds of operations) that fit your last flatMap example?
It can be any function which may succeed or fail depending on conditions.
Following example is taken from real project code:
private static Optional<Instant> parseInstantCursor(JSONObject params) { return safeString(params, "cursor") .toOptional() .flatMap(source -> Optional.of(source.split(":")) .filter(v -> v.length == 2) .flatMap(HighLevelApiHandler::parseInstant)); } private static Optional<Instant> parseInstant(String[] pair) { return allOf(parseLong(pair[0]).filter(v -> v > 0), parseInt(pair[1]).filter(v -> v >= 0)) .map(Instant::ofEpochSecond); } private static Optional<Long> parseLong(String input) { try { return Optional.of(Long.parseLong(input)); } catch (NumberFormatException e) { return Optional.empty(); } }
This example also shows how looks new coding style mentioned at the beginning of the article.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Thanks for sharing. Could you please provide some examples (i.e. kinds of operations) that fit your last flatMap example?
It can be any function which may succeed or fail depending on conditions.
Following example is taken from real project code:
This example also shows how looks new coding style mentioned at the beginning of the article.