3 ms·
I like this val z = (1..9).map {it * 3} .filter {it < 20} .groupBy {it % 2 == 0} .mapKeys {if (it.key
by Lerc 9y ago
I like this
val z = (1..9).map {it * 3}
.filter {it < 20}
.groupBy {it % 2 == 0}
.mapKeys {if (it.key) "even" else "odd"}
I'd like it more if it said it performed the functions in parallel. If it does this Automagically I'm sold. If it doesn't, is there an easy to use form that does do batch operations like map in parallel?
- guelo 9y agoNo, not parallel. Though it should be possible to add extension functions to Collection that use Java 8's Stream apis to provide that functionality.
- runT1ME 9y agoScala has parallel collections that allow for this, looks exactly the same syntax too.
- fineline 9y agoI guess they're just showing off mapKeys, but couldn't that line be eliminated with: .groupBy {if (it % 2 == 0) "even" else "odd"}
- deleted 9y ago[deleted]
- mike_hearn 9y agoParallel 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.
- romanovcode 9y agoYou should try LINQ on C#.