Hacker News new | past | comments | ask | show | jobs | submit login

Parallel version:

    (1..99).parallelStream()
           .map { it * 3 }
           .filter { it < 20 }
           .collect(Collectors.groupingByConcurrent(Function<Int, String> { 
               if (it % 2 == 0) "even" else "odd" 
           }))
The result is of type ConcurrentMap<String, MutableList<Int>>

A couple of notes about this code:

1. It uses the Java 8 streams API. I'm not sure it'll work on Android. The code you gave uses the Kotlin standard library extension functions, which is a different implementation of map/filter/etc using inline functions. When possible, use the Kotlin versions, which don't create new garbage or methods. But Kotlin's library is less powerful than the Java streams API, which can do automatic parallelism.

2. For this toy example the parallel code will be slower. There is a cost involved in automatically parallelising an operation that won't even begin to pay off until you're working with very large inputs.

3. Due to a bug in how Kotlin's type inference interacts with the Java 8 Streams.collect call, I have to specify the type of the lambda explicitly, which is a bit ugly. Especially as the IDE and compiler don't quite agree, so the IDE renders Function<Int, String> in grey, but if I remove it as suggested, I get a compile error. Such bugs are very rare (in fact Streams.collect is the only place I've seen it happen lately), but do highlight the fact that Kotlin has only been at version one for a year and is still maturing the level of stability you would expect from Java.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: