jucardi / go-streams

Stream Collections for Go. Inspired in Java 8 Streams and .NET Linq
MIT License
308 stars 23 forks source link

Filtering to zero elements and calling ToArray fails #4

Closed carlism closed 3 years ago

carlism commented 3 years ago

Maybe I'm doing something wrong here, but I want an empty list instead of a panic.

    arr := []string{"x", "y", "z"}
    newArr := streams.FromArray(arr).
        Filter(func(str interface{}) bool {
            return len(str.(string)) > 1
        }).
        Map(func(str interface{}) interface{} {
            return strings.ToUpper(str.(string))
        }).
        ToArray().([]string)

changing 1 to 0 gives the correct result... I'm trying to do something similar with incoming json data and sometimes the filter gets rid of all the entries.

jucardi commented 3 years ago

HI @carlism , unfortunately when the filtering results in zero elements, an array is not internally initialized, so this would panic because you are trying to cast a nil reference to a []string

However, you can give a default empty array to the ToArray function so if the result of the operation ends in a nil reference (no elements matched the filter), it returns the default array you passed instead.

So in your last line of code, try this:

        ToArray([]string{}).([]string)

Let me know if it helps

carlism commented 3 years ago

Brilliant! That's exactly what I was looking for. Don't know how I missed that. Thank you!