Map to arraylist kotlin

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.

Читайте также:  Java collection get first

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

Twitter Facebook Google Pinterest

A quick guide how to convert the Map to List in Kotlin in different ways. Example kotlin program to convert from HashMap to List.

1. Overview

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 conversion from map to get the list of keys and values.

Kotlin - Convert Map to List Examples

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.

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.

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

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

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.

Labels:

SHARE:

Twitter Facebook Google Pinterest

About Us

Java 8 Tutorial

  • Java 8 New Features
  • Java 8 Examples Programs Before and After Lambda
  • Java 8 Lambda Expressions (Complete Guide)
  • Java 8 Lambda Expressions Rules and Examples
  • Java 8 Accessing Variables from Lambda Expressions
  • Java 8 Method References
  • Java 8 Functional Interfaces
  • Java 8 — Base64
  • Java 8 Default and Static Methods In Interfaces
  • Java 8 Optional
  • Java 8 New Date Time API
  • Java 8 — Nashorn JavaScript

Java Threads Tutorial

Kotlin Conversions

Kotlin Programs

Java Conversions

  • Java 8 List To Map
  • Java 8 String To Date
  • Java 8 Array To List
  • Java 8 List To Array
  • Java 8 Any Primitive To String
  • Java 8 Iterable To Stream
  • Java 8 Stream To IntStream
  • String To Lowercase
  • InputStream To File
  • Primitive Array To List
  • Int To String Conversion
  • String To ArrayList

Java String API

  • charAt()
  • chars() — Java 9
  • codePointAt()
  • codePointCount()
  • codePoints() — Java 9
  • compareTo()
  • compareToIgnoreCase
  • concat()
  • contains()
  • contentEquals()
  • copyValueOf()
  • describeConstable() — Java 12
  • endsWith()
  • equals()
  • equalsIgnoreCase()
  • format()
  • getBytes()
  • getChars()
  • hashcode()
  • indent() — Java 12
  • indexOf()
  • intern()
  • isBlank() — java 11
  • isEmpty()
  • join()
  • lastIndexOf()
  • length()
  • lines()
  • matches()
  • offsetByCodePoints()
  • regionMatches()
  • repeat()
  • replaceFirst()
  • replace()
  • replaceAll()
  • resolveConstantDesc()
  • split()
  • strip(), stripLeading(), stripTrailing()
  • substring()
  • toCharArray()
  • toLowerCase()
  • transform() — Java 12
  • valueOf()

Spring Boot

$show=Java%20Programs

$show=Kotlin

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,

A quick guide how to convert the Map to List in Kotlin in different ways. Example kotlin program to convert from HashMap to List.

Источник

Оцените статью