Returning a value from a method within a lambda expression

前端 未结 2 721
忘了有多久
忘了有多久 2021-01-07 19:10

I\'m trying to figure out how to return a method value from a lambda expression:

public int findMissingNumber(Collection ints) {
    Single<         


        
2条回答
  •  自闭症患者
    2021-01-07 19:34

    (Is this an instance of the XY problem?)

    The question is about how to return from a lambda inside a forEach. Jon Skeet provided some useful information about findFirst and also cautioned about side effects in a lambda run in parallel -- both excellent points.

    But regarding the original question, I'm still thinking: what problem are you trying to solve?

    The method name findMissingNumber in the example is suggestive. The method takes a collection of numbers as a parameter and iterates over it while incrementing a counter. It returns when it finds a mismatch, or it returns -1 if there is no mismatch. Since the counter is incremented once as each value in the ints collection is processed, it seems like that collection is expected to be in order, unless a number is missing.

    If so, the parameter ought to be a List instead of a Collection. (Making a big assumption here.) Under this assumption, one could rewrite the code using lambdas as streams like so:

    static OptionalInt findMissingNumber(List ints) {
        return
            IntStream.rangeClosed(1, ints.size())
                .filter(i -> i != ints.get(i-1))
                .findFirst();
    }
    

    Instead of incrementing a counter, we use IntStream.range to generate the values expected to be in the list. We then rely on random access to the list to get values from their expected positions in the list. We filter for the mismatches and return the first one, if any. This avoids mutation and so should run correctly in parallel. (Note that this doesn't parallelize well if the list isn't random-access, though.)

    The return value is an OptionalInt which is empty if no mismatch was found. This is more explicit than using a sentinel value like -1 to indicate the "not found" condition.

提交回复
热议问题