- Kotlin FP : Convert List<String> to Map<String,Int>
- Kotlin FP : Convert List<String> to Map<String,Int>
- Kotlin: How convert from Set to Map?
- Kotlin convert csv to map <String, List>
- How to convert Object(with value) into Map
- Collection transformation operations
- Map
- Zip
- Associate
- Flatten
- String representation
Kotlin FP : Convert List<String> to Map<String,Int>
Override the object’s to return «Kotlin list string to map» example The is used in string templates (That’s directly writing the name of a variable, the value will be used later to be concatenated) with other strings) But each function has a specific purpose, in terms of how they process the collection and what they return: — returns a new value for each item — returns the original items (allows you to do something with each, then continue processing the collection) — returns nothing (allows you to do something with each, but as a final operation — you can’t chain another operation, it’s terminal ) — returns a subset of the original items, matching a predicate — returns a single item, matching a predicate — returns a single item, transforming the values to produce a single result — returns a single item, based on an attribute of the collection (not the values themselves)
Kotlin FP : Convert List<String> to Map<String,Int>
I have a List of String, I want to transform into a Map of occurrences. ( ~ The Map values are the count of many times the String was repeated in the List)
The imperative way, I’d write like the following
fun transformMap(list: List): Map < val map = mutableMapOf() for(n in list) < map.put(n,map.getOrDefault(n,0) + 1) >return map.toMap() >
How to write this in Functional Programming way ?
In Java 8+, this will be written like this
String[] note; Map noteMap = Arrays.stream(note) .collect(groupingBy(Function.identity(), collectingAndThen(counting(), Long::intValue)));
You can use Kotlin’s Grouping to do this in one line via the Iterable.groupingBy extension:
val myList = listOf("a", "b", "c", "a", "b", "a") val myMap = myList.groupingBy < it >.eachCount() println(myMap) // Prints
You can use streams in Kotlin too. But if you want to avoid streams, you can use fold() :
val list = listOf("a", "b", "c", "a") val histogram = list.fold(mutableMapOf()) < map, s ->map[s] = map.getOrDefault(s, 0) + 1 map >.toMap() println(histogram)
Kotlin: How convert from Set to Map?, 23 hours ago· 1. Just use associateBy extension function: val result: Map
Kotlin: How convert from Set to Map?
I have Set and I need to convert it to Map, FlagFilter> .
I tried doing it like this:
val result: Map, FlagFilter> = target .takeIf < !it.isEmpty() >?.map < mapOf(it.javaClass to it) >?: emptyMap<>()
but instead of a Map it turns out to be a List and I get a compilation error:
Type mismatch. Required: Map, FlagFilter> Found: List, FlagFilter>>
What am I doing wrong? As if there is not enough operation, but I do not understand yet which one
map isn’t anything to do with the Map type — it’s a functional programming term (coming from a broader mathematical concept) that basically means a function that maps each input value to an output value.
So it’s a transformation or conversion that takes a collection of items, transforms each one, and results in another collection with the same number of items. In Kotlin, you get a List of items (unless you’re working with a Sequence , in which case you get another Sequence that yields the same number of items).
It’s worth getting familiar with the kotlin.collections package — there’s lots of useful stuff in there! But each function has a specific purpose, in terms of how they process the collection and what they return:
- map — returns a new value for each item
- onEach — returns the original items (allows you to do something with each, then continue processing the collection)
- forEach — returns nothing (allows you to do something with each, but as a final operation — you can’t chain another operation, it’s terminal )
- filter — returns a subset of the original items, matching a predicate
- first — returns a single item, matching a predicate
- reduce — returns a single item, transforming the values to produce a single result
- count — returns a single item, based on an attribute of the collection (not the values themselves)
There’s more but you get the idea — some things transform, some things pass-through, some things give you an identically sized collection, or a potentially smaller one, or a single value. map is just the one that takes a collection, and gives you a collection of the same size where every item has been (potentially) altered.
Like Vadik says, use one of the associate* functions to turn values into a Map object, effectively transforming each item in the collection into a Map.Entry . Which is technically mapping it to a mapping, so I wasn’t totally accurate earlier when I said it’s nothing to do with Map s, but I figured I’d save this thought til the end 😉
val result: Map, FlagFilter> = target.associateBy
Or if you want to fix your code, remove the excessive call of mapOf(). Just convert your Set to List of Pairs, and then call toMap() to create a map:
val result: Map, FlagFilter> = target.map < it.javaClass to it >.toMap()
Kotlin: transform a list of objects into a map of object, With the first flatMap we transform the albums list ( List
Kotlin convert csv to map <String, List>
US;Americas CA;Americas FR;Europe CH;Asia .
I want to have Map of -> String, List, is it possible to achieve this via associate, or something else ?
but this is just mapping the region to only one code, also tried
Americas -> US, CA, BR . Europe -> FR, IT, CH . Asia -> CH, JP, KR .
associate would replace the value if the key already iterated. You can instead use groupBy to specify key and value for the map
Alternatively to sidgate’s excellent answer you could also do
It avoids having to create a map first, but calls split more often. I’m not sure what would be better in terms of speed/efficiency.
Kotlin convert csv to map, Kotlin add item to top of List
How to convert Object(with value) into Map
I have a object that I want to print it into string Kotlin list string to map without the null value key value pair and comma into &.
So first of all i think of putting it into a map but it won’t work and I don know how it work either.
val wxPayOrderObj = WxPayOrder(appid = "wx0b6dcsad20b379f1", mch_id = "1508334851", nonce_str = UUID.randomUUID().toString(),sign = null, body = "QQTopUp", out_trade_no = "20150806125346", total_fee = req.total_fee, spbill_create_ip = "123.12.12.123", trade_type = "JSAPI", openid = "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o")
appid=wx0b6dc78d20b379f1&mch_id=150788851&nonce_str=UUID.randomUUID().toString()& body=QQTopUp&out_trade_no=20150806125346&total_fee=req.total_fee& spbill_create_ip=123.12.12.123&trade_type=JSAPI&openid=oUpF8uMuAJO_M2pxb1Q9zNjWeS6o
anyone please help me, thanks in advances.
I don’t really get your question, but you want to convert object to string (to a format that you want)?
Override the object’s toString() to return «Kotlin list string to map»
The $ is used in string templates (That’s directly writing the name of a variable, the value will be used later to be concatenated) with other strings)
Kotlin: How to convert list to map with list?, I want to convert it to a map of list as below <("a" (1, 4)), ("b", (2)), ("c", (3)))>i.e. for a, we have a list of 1 and 4, since the key is the same. The answer in How to convert List to Map in Kotlin? only show unique value (instead of …
Collection transformation operations
The Kotlin standard library provides a set of extension functions for collection transformations. These functions build new collections from existing ones based on the transformation rules provided. In this page, we’ll give an overview of the available collection transformation functions.
Map
The mapping transformation creates a collection from the results of a function on the elements of another collection. The basic mapping function is map() . It applies the given lambda function to each subsequent element and returns the list of the lambda results. The order of results is the same as the original order of elements. To apply a transformation that additionally uses the element index as an argument, use mapIndexed() .
If the transformation produces null on certain elements, you can filter out the null s from the result collection by calling the mapNotNull() function instead of map() , or mapIndexedNotNull() instead of mapIndexed() .
When transforming maps, you have two options: transform keys leaving values unchanged and vice versa. To apply a given transformation to keys, use mapKeys() ; in turn, mapValues() transforms values. Both functions use the transformations that take a map entry as an argument, so you can operate both its key and value.
Zip
Zipping transformation is building pairs from elements with the same positions in both collections. In the Kotlin standard library, this is done by the zip() extension function.
When called on a collection or an array with another collection (or array) as an argument, zip() returns the List of Pair objects. The elements of the receiver collection are the first elements in these pairs.
If the collections have different sizes, the result of the zip() is the smaller size; the last elements of the larger collection are not included in the result.
zip() can also be called in the infix form a zip b .
You can also call zip() with a transformation function that takes two parameters: the receiver element and the argument element. In this case, the result List contains the return values of the transformation function called on pairs of the receiver and the argument elements with the same positions.
When you have a List of Pair s, you can do the reverse transformation – unzipping – that builds two lists from these pairs:
- The first list contains the first elements of each Pair in the original list.
- The second list contains the second elements.
To unzip a list of pairs, call unzip() .
Associate
Association transformations allow building maps from the collection elements and certain values associated with them. In different association types, the elements can be either keys or values in the association map.
The basic association function associateWith() creates a Map in which the elements of the original collection are keys, and values are produced from them by the given transformation function. If two elements are equal, only the last one remains in the map.
For building maps with collection elements as values, there is the function associateBy() . It takes a function that returns a key based on an element’s value. If two elements’ keys are equal, only the last one remains in the map.
associateBy() can also be called with a value transformation function.
Another way to build maps in which both keys and values are somehow produced from collection elements is the function associate() . It takes a lambda function that returns a Pair : the key and the value of the corresponding map entry.
Note that associate() produces short-living Pair objects which may affect the performance. Thus, associate() should be used when the performance isn’t critical or it’s more preferable than other options.
An example of the latter is when a key and the corresponding value are produced from an element together.
Here we call a transform function on an element first, and then build a pair from the properties of that function’s result.
Flatten
If you operate nested collections, you may find the standard library functions that provide flat access to nested collection elements useful.
The first function is flatten() . You can call it on a collection of collections, for example, a List of Set s. The function returns a single List of all the elements of the nested collections.
Another function – flatMap() provides a flexible way to process nested collections. It takes a function that maps a collection element to another collection. As a result, flatMap() returns a single list of its return values on all the elements. So, flatMap() behaves as a subsequent call of map() (with a collection as a mapping result) and flatten() .
String representation
If you need to retrieve the collection content in a readable format, use functions that transform the collections to strings: joinToString() and joinTo() .
joinToString() builds a single String from the collection elements based on the provided arguments. joinTo() does the same but appends the result to the given Appendable object.
When called with the default arguments, the functions return the result similar to calling toString() on the collection: a String of elements’ string representations separated by commas with spaces.
To build a custom string representation, you can specify its parameters in function arguments separator , prefix , and postfix . The resulting string will start with the prefix and end with the postfix . The separator will come after each element except the last.
For bigger collections, you may want to specify the limit – a number of elements that will be included into result. If the collection size exceeds the limit , all the other elements will be replaced with a single value of the truncated argument.
Finally, to customize the representation of elements themselves, provide the transform function.