Learning Kotlin: Collections
Learning Kotlin: Collections
Want to learn more about using Collections in Kotlin? This post has everything you need to know Collections and the extension methods that exist.
Join the DZone community and get the full member experience.Join For Free
Delivering modern software? Atomist automates your software delivery experience.
The Koans for Kotlin are broken into sections and our earlier posts have covered the first section; this post is going to cover the entire second section. The reasons we are not breaking this down as we did before is because the common theme here is working the
kotlin.collections and in particular the wealth of extension methods that exist.
|Koan||Functions||What it does?||C# Equivalent||Notes|
|Filter and Map||Map & Filter||Map is a projection - it allows you to take in a collection of items and change each time. It is useful for selecting properties of objects in a collection. Filter lets you filter a collection||Map is the same as select and filter is the same as where|
|All Any And Other Predicates||any, all, count and firstOrNull||Any returns true if it finds one any match to the provided expression. All requires all items in the collection to match the provided expression. Count provides the size of the collection. FirstOrNull returns the first item in a collection which matches the expression or, if nothing does, it returns null||any, all, count and firstOrDefault||Any, all and count work the same as in .NET. Count should be avoided when
|Flatmap||flatMap||Where map returns a collection which has the same size as the input, however flatMap the resulting collection can be a different size from the input||selectMany|
|Max and min||max and maxBy||MaxBy returns the largest value in the collection by letting you select which property to use for the ordering||Max||Interesting that .NET uses one function name to do with Kotlin uses max and maxBy to do both.|
|sort||sortBy||SortBy lets your sort the collection with an O(n2) performance||orderBy|
|GroupBy||groupBy||returns a map (or dictionary) where the key is one provided by the expression and the value is the items from the input collection which match the expression||GroupBy|
|Partition||partition||Partition returns a Pair with a list in both values and the expression defines what goes into each value. Basically you are splitting a collection||No direct option for this. You could use take if you only cared about half the collection.|
|Fold||fold||Allows you to produce a single value from a collection; normally aggregation - for example adding up all values in an array.||aggregate|
Going through these exercises was really interesting and I'm glad there is a lot of similar functionality to .NETs LINQ functions. The code being referenced can be found here.
Published at DZone with permission of Robert Maclean , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.