Kotlin map values to list

Android & Kotlin Examples code

Android kotlin tutorials and examples code for android apps developers.

How to Convert Map (HashMap) to List in Kotlin Android

This example Program to Convert Map (HashMap) to List in Kotlin Android

package com.example.espl.hashmaptolistkotlin
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import java.security.KeyPair

class MainActivity : AppCompatActivity() // fun hashMapOf(): HashMap
// Returns an empty new HashMap.
//Method hashMapOf() in Kotlin
val hashMap: HashMap = hashMapOf()

override fun onCreate(savedInstanceState: Bundle?) super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

hashMap.put(1,»Value1″)
hashMap.put(2,»Value2″)
hashMap.put(3,»Value3″)
hashMap.put(4,»Value4″)
hashMap.put(5,»Value5″)
//print hash map in Log
Log.e(«hashmap»,»::»+hashMap)

// Returns a [List] containing all key-value pairs.
// public fun Map.toList(): List
// Convert Kotlin Map to List using toList() method
val pairKeyValueList : List> = hashMap.toList();
Log.e(«HashmapPairKeyValueList»,»::»+pairKeyValueList)

// Convert Kotlin Map to List of keys after extracting the keys
//public Set keySet() method return a set view of the keys contained in this map
val listKeys : Set = hashMap.keys
//Convert the returned set to ArrayList
val arraListOfKeys: List = ArrayList(listKeys.toList())
Log.e(«hashmap:arraListOfKeys»,»::»+arraListOfKeys)

// Convert Kotlin Map to List after extracting the values
//public Collection values() method return a view of the values contained in this map
val listValues = hashMap.values
//Convert the returned Collection to ArrayList
val arraListOfvalues: List = ArrayList(listValues.toList())
Log.e(«hashmap:arraListOfvalues»,»::»+arraListOfvalues)

val students:HashMap = hashMapOf()
students.put(1, Student(«Ram», «VI», Address(«New street», «Ahmedabad»)))
students.put(2, Student(«Raju», «V», Address(«Green cross», «Rajkot»)))

val pairKeyValueListStudents:ArrayList> = ArrayList(students.toList())
Log.e(«HashmapPairKeyValueList»,»::»+pairKeyValueListStudents)

val listKeysStudents: Set = students.keys
Log.e(«map:listKeysStudents»,»::»+listKeysStudents)

//public Collection values() method return a view of the values(student objects) contained in this map
val listValuesStudents:ArrayList = ArrayList(students.values)
Log.e(«listValuesStudents»,»::»+listValuesStudents)

val listValuesStudentsAddress:ArrayList = ArrayList(students.values.map < x->x.address>)
Log.e(«listValStudentsAddress»,»::»+listValuesStudentsAddress)

// While working with Map Object, we can associate with map(transform: (T) -> R) function to customise a returned-list
val listValuesStudentsCity: List = students.values.map < x->x.address.city>
Log.e(«listValuesStudentsCity»,»::»+listValuesStudentsCity)
>

data class Address(
var street : String? = null,
var city : String? = null
)<>

data class Student(
var name: String? = null,
var std: String? = null,
var address: Address = Address()) >
>

com.example.espl.hashmaptolistkotlin E/hashmap: ::
com.example.espl.hashmaptolistkotlin E/HashmapPairKeyValueList: ::[(4, Value4), (1, Value1), (5, Value5), (3, Value3), (2, Value2)]
com.example.espl.hashmaptolistkotlin E/hashmap:arraListOfKeys: ::[4, 1, 5, 3, 2]
com.example.espl.hashmaptolistkotlin E/hashmap:arraListOfvalues: ::[Value4, Value1, Value5, Value3, Value2]
com.example.espl.hashmaptolistkotlin E/HashmapPairKeyValueList: ::[(1, Student(name=Ram, std=VI, address=Address(street=New street, city=Ahmedabad))), (2, Student(name=Raju, std=V, address=Address(street=Green cross, city=Rajkot)))]

com.example.espl.hashmaptolistkotlin E/map:listKeysStudents: ::[1, 2]
com.example.espl.hashmaptolistkotlin E/listValuesStudents: ::[Student(name=Ram, std=VI, address=Address(street=New street, city=Ahmedabad)), Student(name=Raju, std=V, address=Address(street=Green cross, city=Rajkot))]

com.example.espl.hashmaptolistkotlin E/listValStudentsAddress: ::[Address(street=New street, city=Ahmedabad), Address(street=Green cross, city=Rajkot)]
com.example.espl.hashmaptolistkotlin E/listValuesStudentsCity: ::[Ahmedabad, Rajkot]

Источник

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.

Источник

Kotlin – Convert Map to List Examples

In this tutorial, We will learn how to convert the Map to List in kotlin programming. Map implementations such as HashMap or TreeMap can be converted into an ArrayList or List object.

Let us explore the
different ways to do this conversion.

2. Converting HashMap to List in Kotlin Using ArrayList Constructor

This approach is the simple one and easy. First create the HashMap object with HashMap() constructor.

Next, adding few key value pairs to the map. Use map.keys and map.values to get the all keys and values.

Pass these values to ArrayList constructor to convert the map to list.

These properties will be invoking the below functions internally when you are using java.util.HashMap.

package com.javaprogramto.kotlin.collections.map.list import java.util.HashMap fun main(array: Array) < var map = HashMap(); map.put(10, "Ten") map.put(20, "Twenty") map.put(30, "Thirty") map.put(40, "Fourty") map.put(50, "Fifty") var keysList = ArrayList(map.keys); var valuesList = ArrayList(map.values); println("Keys list : $keysList") println("Values list : $valuesList") >
Keys list : [50, 20, 40, 10, 30] Values list : [Fifty, Twenty, Fourty, Ten, Thirty]

3. Converting LinkedHashMap to List in Kotlin Using ArrayList Constructor

From the above program, the output is not in the order what is inserted into the map. To preserve the insertion order then need to use LinkedHashMap class instead of HashMap.

Look at the below program and observer the output order.

package com.javaprogramto.kotlin.collections.map.list import java.util.HashMap fun main(array: Array) < // to holds the insertion order var map = LinkedHashMap(); map.put(10, "Ten") map.put(20, "Twenty") map.put(30, "Thirty") map.put(40, "Fourty") map.put(50, "Fifty") // gets the keys and values as per the insertion var keysList = ArrayList(map.keys); var valuesList = ArrayList(map.values); // prints println("Keys list : $keysList") println("Values list : $valuesList") >
Keys list : [10, 20, 30, 40, 50] Values list : [Ten, Twenty, Thirty, Fourty, Fifty]

4. Kotlin Map to List using toList() method

Use toList() method on map object or keys, values properties.

package com.javaprogramto.kotlin.collections.map.list import java.util.HashMap fun main(array: Array) < var map = HashMap(); map[10] = "Ten" map[20] = "Twenty" map[30] = "Thirty" map[40] = "Fourty" map[50] = "Fifty" // example 1 using toList() method var keysList = map.keys.toList(); var valuesList = map.values.toList(); println("using toList()") println("Keys list : $keysList") println("Values list : $valuesList") // example 2 using toList() method var mutableMap: MutableMap = HashMap() mutableMap[10] = "Ten" mutableMap[20] = "Twenty" mutableMap[30] = "Thirty" mutableMap[40] = "Fourty" mutableMap[50] = "Fifty" var entries = mutableMap.toList().map < "($, $)"> println("\nusing toList() on mutable map") entries.forEach >
using toList() Keys list : [50, 20, 40, 10, 30] Values list : [Fifty, Twenty, Fourty, Ten, Thirty] using toList() on mutable map (50, Fifty) (20, Twenty) (40, Fourty) (10, Ten) (30, Thirty)

5. Kotlin Map to List using entries properties

map.entries properties will returns the key-value pairs. Use map() method on the entries object. We can use the any pattern in between the key and value.

package com.javaprogramto.kotlin.collections.map.list import java.util.HashMap fun main(array: Array) < var mutableMap: MutableMap= HashMap() mutableMap[10] = "Ten" mutableMap[20] = "Twenty" mutableMap[30] = "Thirty" mutableMap[40] = "Fourty" mutableMap[50] = "Fifty" var list : List = mutableMap.entries.map < ("$--> $") > list.forEach >
50 --> Fifty 20 --> Twenty 40 --> Fourty 10 --> Ten 30 --> Thirty

6. Kotlin Map to List using keys and values

Use keys and values properties of map object to call map() method.

package com.javaprogramto.kotlin.collections.map.list import java.util.HashMap fun main(array: Array) < var mutableMap: MutableMap= HashMap() mutableMap[10] = "Ten" mutableMap[20] = "Twenty" mutableMap[30] = "Thirty" mutableMap[40] = "Fourty" mutableMap[50] = "Fifty" var keysList : List = mutableMap.keys.map < ("$") > var valuesList : List = mutableMap.values.map < ("$") > println("---- keys list ------") keysList.forEach println("----- values list ------") valuesList.forEach >
---- keys list ------ 50 20 40 10 30 ----- values list ------ Fifty Twenty Fourty Ten Thirty

7. Conclusion

in this article, We have seen how to convert Map to List in Kotlin programming and examples on different approaches.

Published on Java Code Geeks with permission by Venkatesh Nukala, partner at our JCG program. See the original article here: Kotlin – Convert Map to List Examples

Источник

Читайте также:  Gold цвет в html
Оцените статью