Kotlin transform map to map

Kotlin transform map to map

Оператор map() преобразует данные потока. В качестве параметра он принимает функцию преобразования. Функция преобразования принимает в качестве единственного параметра объект из потока и возвращает преобразованные данные.

inline fun Flow.map( crossinline transform: suspend (value: T) -> R ): Flow (source)
import kotlinx.coroutines.flow.* suspend fun main() < val peopleFlow = listOf( Person("Tom", 37), Person("Sam", 41), Person("Bob", 21) ).asFlow() peopleFlow.map< person ->person.name > .collect < personName ->println(personName) > > data class Person(val name: String, val age: Int)

В данном случае определяем поток данных peopleFlow , который содержит объекты типа Person . Далее к этому потоку применяется функция map() , в которую передается следующая функция преобразования:

То есть функция преобразования принимает в качестве параметра person объект типа Person и возвращает значение его поля name — то есть строку. Таким образом, функция map() из потока объектов Person создаст поток обектов String.

Далее к полученному потоку объектов String применяем функцию collect() , в которой получаем каждую строку из потока и выводим ее на консоль:

collect < personName ->println(personName) >

Консольный вывод программы:

import kotlinx.coroutines.flow.* suspend fun main() < val peopleFlow = listOf( Person("Tom", 37), Person("Bill", 5), Person("Sam", 14), Person("Bob", 21), ).asFlow() peopleFlow.map< person ->object < val name = person.name val isAdult = person.age >17 >>.collect < user ->println("name: $ adult: $ ")> > data class Person(val name: String, val age: Int)

В данном случае функция map преобразует поток данных типа Person в поток объектов анонимного типа, который определяет два поля: name (имя) и isAdult (больше ли пользователю 17 лет). Соответственно в функции collect мы получаем объекты этого анонимного типа и выводим их данные на консоль. Консольный вывод:

name: Tom adult: true name: Bill adult: false name: Sam adult: false name: Bob adult: true

Функция transform

Оператор transform также позволяет выполнять преобразование объектов в потоке. В отличие от map она позволяет использовать функцию emit() , чтобы передавать в поток произвольные объекты.

inline fun Flow.transform( crossinline transform: suspend FlowCollector.(value: T) -> Unit ): Flow (source)

Оператор transform принимает функцию, которая получает в качестве параметра объект потока. Например:

import kotlinx.coroutines.flow.* suspend fun main() < val peopleFlow = listOf( Person("Tom", 37), Person("Bill", 5), Person("Sam", 14), Person("Bob", 21), ).asFlow() peopleFlow.transform< person ->if(person.age > 17) < emit(person.name) >>.collect < personName ->println(personName)> > data class Person(val name: String, val age: Int)

В данном случае получаем в функции transform объект Person из потока. Если поле age этого объекта больше 17, то передаем его в новый поток через функцию emit() . Консольный вывод программы:

Причем при обработке одного объекта мы можем несколько раз вызывать функцию emit() , передавая таким образом в потоке несколько объектов:

import kotlinx.coroutines.flow.* suspend fun main() < val numbersFlow = listOf(2, 3, 4).asFlow() numbersFlow.transform< n ->emit(n) emit(n * n) >.collect < n ->println(n)> >

Например, здесь преобразуем поток чисел. Причем в выходной поток передается само число и его квадрат. Таким образом, на консоли мы увидим:

Источник

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 transform map to map

@ExperimentalUnsignedTypes inline fun < R > ULongArray . map (
transform : ( ULong ) -> R
) : List < R >
(source)

@ExperimentalUnsignedTypes inline fun < R > UByteArray . map (
transform : ( UByte ) -> R
) : List < R >
(source)

@ExperimentalUnsignedTypes inline fun < R > UShortArray . map (
transform : ( UShort ) -> R
) : List < R >
(source)

Returns a list containing the results of applying the given transform function to each element in the original array.

import kotlin.test.* fun main(args: Array) < //sampleStart val numbers = listOf(1, 2, 3) println(numbers.map < it * it >) // [1, 4, 9] //sampleEnd >

Returns a list containing the results of applying the given transform function to each element in the original collection.

import kotlin.test.* fun main(args: Array) < //sampleStart val numbers = listOf(1, 2, 3) println(numbers.map < it * it >) // [1, 4, 9] //sampleEnd >

Returns a list containing the results of applying the given transform function to each entry in the original map.

import kotlin.test.* import java.util.* fun main(args: Array) < //sampleStart val peopleToAge = mapOf("Alice" to 20, "Bob" to 21) println(peopleToAge.map < (name, age) ->"$name is $age years old" >) // [Alice is 20 years old, Bob is 21 years old] println(peopleToAge.map < it.value >) // [20, 21] //sampleEnd >

Источник

Kotlin transform map to map

Для трансформации одной коллекции/последовательности применяется функция 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]

Источник

Читайте также:  Javascript значения всех свойств объекта
Оцените статью