0

Imagine hierarchical path stored in ordered List and its validation

List<String> path = Lists.newArrayList("path","to","end");

Iterator<String> iterator = path.iterator();

while (iterator.hasNext()) {
    if (iterator.next() == null) {
        while (iterator.hasNext()) {
            if (iterator.next() != null) {
                throw new Exception("Invalid path");
            }
        }
    }
}

The algorithm is pretty straightforward.

Only leafs or nodes with all its descendant must be null.

Valid paths:

"path", "to", "end"
"path", "to", null
"path", null, null
null, null, null

Invalid paths:

"path", null, "end"
null, null, "end"
null, "to", "end"
null, "to", null

I am looking for way to rewrite it in a functional style.

3
  • 1
    I think you've got some typos in your "valid paths" which are making your question confusing. Did you mean to put quotes around null is those places? Commented Feb 13, 2017 at 23:53
  • @4castle thx, i fixed the typo Commented Feb 14, 2017 at 8:34
  • What's wrong with non-functional solution? You said it yourself - your imperative algorithm is straightforward and relatively simple (I would only remove a second nested while, since you don't need it). It will gain no benefir from functional rewrite, and most likely will gain only complexity (I'm almost sure that functional implementation would require a Tuple class, for example). Commented Feb 14, 2017 at 15:32

1 Answer 1

3

In Java 9, you could use

if(path.stream().dropWhile(Objects::nonNull).anyMatch(Objects::nonNull))
    throw new Exception("Invalid path");

The logic is simple, first, drop all non-null values until the encounter of a null value (if any), then, fail if any non-null value follows.

Since Java 8 lacks the dropWhile operation, we have to prepend an alternative operation, e.g. using the Collection API rather than Stream API:

int firstNull = path.indexOf(null);
if(firstNull>=0 && path.stream().skip(firstNull).anyMatch(Objects::nonNull))
    throw new Exception("Invalid path");
Sign up to request clarification or add additional context in comments.

2 Comments

as you have been among the top users in Java-8, would you please put some links about that Java-9 feature? :)
@Jude Niroshan: Here you go

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.