Kotlin map list to another list
Для трансформации одной коллекции/последовательности применяется функция map()
map(transform: (T) -> R): List/Sequence
В качестве параметра она принимает функцию пребразования. Функция пребразования получает текущий элемент коллекции/последовательности и возвращает результат преобразования. Причем типа входных и выходных данных могут совпадать, а могут и отличаться. Например:
fun main() < val people = listOf(Person("Tom"), Person("Sam"), Person("Bob")) val names = people.map < it.name >// возвращаем имя каждого пользователя println(names) // [Tom, Sam, Bob] > class Person(val name: String)
Здесь из списка List получаем список List, который содержит имена пользователей.
Другой пример — трансформируем последовательность чисел в последовательность квадратов этих чисел:
val numbers = listOf(1, 2, 3, 4, 5) val squares = numbers.map < it * it >println(squares) // [1, 4, 9, 16, 25]
Еще одна функция — mapIndexed() также передает в функцию преобразования индекс текущего элемента:
mapIndexed(transform: (index: Int, T) -> R): List
fun main() < val people = listOf(Person("Tom"), Person("Sam"), Person("Bob")) val names = people.mapIndexed< index, p->"$.$"> println(names) // [1.Tom, 2.Sam, 3.Bob] > class Person(val name: String)
Если необходимо отсеять значения null, которые могут возникать при преобразовании, то можно применять аналоги выше упомянутых функций — mapNotNull() и mapIndexedNotNull() :
fun main() < val people = listOf( Person("Tom"), Person("Sam"), Person("Bob"), Person("Alice") ) // элементы длиной имени не равной 3 преобразуем в null val names1 = people.mapNotNull< if(it.name.length!=3) null else it.name >// элементы на четных позициях преобразуем в null val names2 = people.mapIndexedNotNull < index, p ->if(index%2==0) null else p.name > println(names1) // [Tom, Sam, Bob] println(names2) // [Sam, Alice] > class Person(val name: String)
flatten
Функция flatten() позволяет преобразовать коллекцию/последовательность, которая содержит вложенные коллекции/последовательности:
Эта функция помещает элементы всех вложенных коллекций в одну:
val personal = listOf(listOf("Tom", "Bob"), listOf("Sam", "Mike", "Kate"), listOf("Tom", "Bill")) val people = personal.flatten() println(people) // [Tom, Bob, Sam, Mike, Kate, Tom, Bill]
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.
map a nested list to another nested list in Kotlin
I have a nested list of People : List, where People has two attribute int age, String name. I want to map it to a nested list of Student, Student also has two attribute int age, String name. So the output is List>.I have looked at examples of mapping a List to another, something like this:
1 Answer 1
map is one of Kotlin’s collection transformation operations. That link explains how it works.
Let’s fix your List.convert() function first. Here’s one way to write it:
data class Person(val name: String, val age: Int) data class Student(val name: String, val age: Int) fun List.convert(): List < return this.map < person ->Student( age = person.age, name = person.name, ) > >
Note that inside the mapping function, this does not refer to anything, which is why your original code doesn’t compile.
Since the mapping function we’re passing to map has only one parameter, we can skip declaring the parameter, and refer to the argument by the special name it instead, like this:
Then, to convert a List> to a List> we could write:
val listsOfPeople: List> = listOf( listOf(Person("Alice", 27)), listOf(Person("Bob", 23), Person("Clarissa", 44)) ) val listsOfStudents: List> = listsOfPeople.map < // it is Listit.convert() >
Or, if you decide you don’t need the convert function, you could write it like this:
val listsOfStudents: List> = listsOfPeople.map < // it is Listit.map < // it is Person Student(it.name, it.age) >>
Kotlin Is there a way to flatten Map to List
order must be Key and its Values, Key and its Values, . is there some function in kotlin that could help me with that?
there is no way that you ever get such a list out of that map. The reason is, that when you create the map this way you actually get a map containing: «a» with 2 and «b» with value 4 . Otherwise: yes. you can flatten it. maybe with something like: mapOf(. ).flatMap < (string, int) ->listOf(string, int) > or similar. map.flatMap < (string, ints) ->listOf(string).plus(ints) >
@Roland sorry my bad, I updated question. Your map.flatMap < (string, ints) ->listOf(string).plus(ints) > works well for me. thanks
3 Answers 3
My second comment variant as answer for a Map> :
mapOf("a" to listOf(1,2), "b" to listOf(3,4)) .flatMap < (key, values) ->listOf(key) + values >
which gives a List with the keys followed by their values.
UPDATE: the answer below was written before the question was updated and changed how the map was created (see the history of the question for details). As the question now stands, the answer below will no longer work. It does work for the question as originally asked though, I believe.
@Roland is right that your map will never result in that list because there can only ever be a single value in the map against any given key. So I think you need to replace that map with a list of pairs. You can then group it and flatmap it to get your desired result:
val pairs = listOf("a" to 1, "a" to 2, "b" to 3, "b" to 4) val result = pairs .groupBy < it.first >.flatMap < (key, values) ->listOf(key).plus(values.map < it.second >) >
Another slightly different option which you might decide is more readable is this:
val result = pairs .groupBy(< it.first >, < it.second >) .flatMap < (key, values) ->listOf(key).plus(values) >