Kotlin list map to set

Kotlin Convert List to Set

Sets are collections that allow only one element of each value.

A Set automatically prevents duplicates.

val colors = "Yellow Green Green Blue".split (Regex ("""\W+""")).sorted ()//[1] fun main () < println(colors) val colorSet = colors.toSet () // [2] println(colorSet) println(colorSet + colorSet) // [3] val mSet = colorSet.toMutableSet () // [4] mSet -= "Blue" mSet += "Red" // [5] println(mSet) // Set membership : println(("Green" in colorSet)) // [6] println(colorSet.contains("Red") ) >
[1] The String is split() using a regular expression.

[2] When colors is copied into the read-only Set colorSet, one of the two «Green» Strings is removed, because it is a duplicate. [3] Here we create and display a new Set using the + operator.

Placing duplicate items into a Set automatically removes those duplicates.

[4] toMutableSet() produces a new MutableSet from a read-only Set. [5] For a MutableSet, the operators += and -= add and remove elements, as they do with MutableLists. [6] Test for Set membership using in or contains() The normal mathematical set operations such as union, intersection, difference, etc., are all available.

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

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.

Источник

Collections overview

The Kotlin Standard Library provides a comprehensive set of tools for managing collections – groups of a variable number of items (possibly zero) that are significant to the problem being solved and are commonly operated on.

Collections are a common concept for most programming languages, so if you’re familiar with, for example, Java or Python collections, you can skip this introduction and proceed to the detailed sections.

A collection usually contains a number of objects (this number may also be zero) of the same type. Objects in a collection are called elements or items. For example, all the students in a department form a collection that can be used to calculate their average age.

The following collection types are relevant for Kotlin:

  • List is an ordered collection with access to elements by indices – integer numbers that reflect their position. Elements can occur more than once in a list. An example of a list is a telephone number: it’s a group of digits, their order is important, and they can repeat.
  • Set is a collection of unique elements. It reflects the mathematical abstraction of set: a group of objects without repetitions. Generally, the order of set elements has no significance. For example, the numbers on lottery tickets form a set: they are unique, and their order is not important.
  • Map (or dictionary) is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value. The values can be duplicates. Maps are useful for storing logical connections between objects, for example, an employee’s ID and their position.

Kotlin lets you manipulate collections independently of the exact type of objects stored in them. In other words, you add a String to a list of String s the same way as you would do with Int s or a user-defined class. So, the Kotlin Standard Library offers generic interfaces, classes, and functions for creating, populating, and managing collections of any type.

The collection interfaces and related functions are located in the kotlin.collections package. Let’s get an overview of its contents.

Collection types

The Kotlin Standard Library provides implementations for basic collection types: sets, lists, and maps. A pair of interfaces represent each collection type:

  • A read-only interface that provides operations for accessing collection elements.
  • A mutable interface that extends the corresponding read-only interface with write operations: adding, removing, and updating its elements.

Note that altering a mutable collection doesn’t require it to be a var : write operations modify the same mutable collection object, so the reference doesn’t change. Although, if you try to reassign a val collection, you’ll get a compilation error.

The read-only collection types are covariant. This means that, if a Rectangle class inherits from Shape , you can use a List anywhere the List is required. In other words, the collection types have the same subtyping relationship as the element types. Maps are covariant on the value type, but not on the key type.

In turn, mutable collections aren’t covariant; otherwise, this would lead to runtime failures. If MutableList was a subtype of MutableList , you could insert other Shape inheritors (for example, Circle ) into it, thus violating its Rectangle type argument.

Below is a diagram of the Kotlin collection interfaces:

Collection interfaces hierarchy

Let’s walk through the interfaces and their implementations. To learn about Collection , read the section below. To learn about List , Set , and Map , you can either read the corresponding sections or watch a video by Sebastian Aigner, Kotlin Developer Advocate:

Collection

fun List.getShortWordsTo(shortWords: MutableList, maxLength: Int) < this.filterTo(shortWords) < it.length // throwing away the articles val articles = setOf("a", "A", "an", "An", "the", "The") shortWords -= articles > fun main() < val words = "A long time ago in a galaxy far far away".split(" ") val shortWords = mutableListOf() words.getShortWordsTo(shortWords, 3) println(shortWords) >

List

List elements (including nulls) can duplicate: a list can contain any number of equal objects or occurrences of a single object. Two lists are considered equal if they have the same sizes and structurally equal elements at the same positions.

As you see, in some aspects lists are very similar to arrays. However, there is one important difference: an array’s size is defined upon initialization and is never changed; in turn, a list doesn’t have a predefined size; a list’s size can be changed as a result of write operations: adding, updating, or removing elements.

In Kotlin, the default implementation of MutableList is ArrayList which you can think of as a resizable array.

Set

MutableSet is a Set with write operations from MutableCollection .

The default implementation of MutableSet – LinkedHashSet – preserves the order of elements insertion. Hence, the functions that rely on the order, such as first() or last() , return predictable results on such sets.

An alternative implementation – HashSet – says nothing about the elements order, so calling such functions on it returns unpredictable results. However, HashSet requires less memory to store the same number of elements.

Map

fun main() < //sampleStart val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1) println("All keys: $«) println(«All values: $») if («key2» in numbersMap) println(«Value by key \»key2\»: $») if (1 in numbersMap.values) println(«The value 1 is in the map») if (numbersMap.containsValue(1)) println(«The value 1 is in the map») // same as previous //sampleEnd >

Two maps containing the equal pairs are equal regardless of the pair order.

MutableMap is a Map with map write operations, for example, you can add a new key-value pair or update the value associated with the given key.

The default implementation of MutableMap – LinkedHashMap – preserves the order of elements insertion when iterating the map. In turn, an alternative implementation – HashMap – says nothing about the elements order.

Источник

Читайте также:  Python machine learning books
Оцените статью