Map or else kotlin

Map-specific operations

In maps, types of both keys and values are user-defined. Key-based access to map entries enables various map-specific processing capabilities from getting a value by key to separate filtering of keys and values. On this page, we provide descriptions of the map processing functions from the standard library.

Retrieve keys and values

For retrieving a value from a map, you must provide its key as an argument of the get() function. The shorthand Map or else kotlin syntax is also supported. If the given key is not found, it returns null . There is also the function getValue() which has slightly different behavior: it throws an exception if the key is not found in the map. Additionally, you have two more options to handle the key absence:

  • getOrElse() works the same way as for lists: the values for non-existent keys are returned from the given lambda function.
  • getOrDefault() returns the specified default value if the key is not found.
Читайте также:  Birthday Reminders for August

To perform operations on all keys or all values of a map, you can retrieve them from the properties keys and values accordingly. keys is a set of all map keys and values is a collection of all map values.

Filter

You can filter maps with the filter() function as well as other collections. When calling filter() on a map, pass to it a predicate with a Pair as an argument. This enables you to use both the key and the value in the filtering predicate.

There are also two specific ways for filtering maps: by keys and by values. For each way, there is a function: filterKeys() and filterValues() . Both return a new map of entries which match the given predicate. The predicate for filterKeys() checks only the element keys, the one for filterValues() checks only values.

Plus and minus operators

Due to the key access to elements, plus ( + ) and minus ( — ) operators work for maps differently than for other collections. plus returns a Map that contains elements of its both operands: a Map on the left and a Pair or another Map on the right. When the right-hand side operand contains entries with keys present in the left-hand side Map , the result map contains the entries from the right side.

minus creates a Map from entries of a Map on the left except those with keys from the right-hand side operand. So, the right-hand side operand can be either a single key or a collection of keys: list, set, and so on.

For details on using plusAssign ( += ) and minusAssign ( -= ) operators on mutable maps, see Map write operations below.

Читайте также:  Вывести определенный элемент массива python

Map write operations

Mutable maps offer map-specific write operations. These operations let you change the map content using the key-based access to the values.

There are certain rules that define write operations on maps:

  • Values can be updated. In turn, keys never change: once you add an entry, its key is constant.
  • For each key, there is always a single value associated with it. You can add and remove whole entries.

Below are descriptions of the standard library functions for write operations available on mutable maps.

Add and update entries

To add a new key-value pair to a mutable map, use put() . When a new entry is put into a LinkedHashMap (the default map implementation), it is added so that it comes last when iterating the map. In sorted maps, the positions of new elements are defined by the order of their keys.

To add multiple entries at a time, use putAll() . Its argument can be a Map or a group of Pair s: Iterable , Sequence , or Array .

Both put() and putAll() overwrite the values if the given keys already exist in the map. Thus, you can use them to update values of map entries.

You can also add new entries to maps using the shorthand operator form. There are two ways:

When called with the key present in the map, operators overwrite the values of the corresponding entries.

Remove entries

To remove an entry from a mutable map, use the remove() function. When calling remove() , you can pass either a key or a whole key-value-pair. If you specify both the key and value, the element with this key will be removed only if its value matches the second argument.

You can also remove entries from a mutable map by their keys or values. To do this, call remove() on the map’s keys or values providing the key or the value of an entry. When called on values, remove() removes only the first entry with the given value.

The minusAssign ( -= ) operator is also available for mutable maps.

Источник

Idioms

A collection of random and frequently used idioms in Kotlin. If you have a favorite idiom, contribute it by sending a pull request.

Create DTOs (POJOs/POCOs)

provides a Customer class with the following functionality:

  • getters (and setters in case of var s) for all properties
  • equals()
  • hashCode()
  • toString()
  • copy()
  • component1() , component2() , . for all properties (see Data classes)

Default values for function parameters

Filter a list

Or alternatively, even shorter:

Learn the difference between Java and Kotlin filtering.

Check the presence of an element in a collection

String interpolation

Instance checks

Read-only list

Read-only map

Access a map entry

Traverse a map or a list of pairs

k and v can be any convenient names, such as name and age .

Iterate over a range

for (i in 1..100) < . >// closed-ended range: includes 100 for (i in 1.. <100) < . >// open-ended range: does not include 100 for (x in 2..10 step 2) < . >for (x in 10 downTo 1) < . >(1..10).forEach < . >

Lazy property

Extension functions

Create a singleton

Instantiate an abstract class

If-not-null shorthand

If-not-null-else shorthand

val files = File(«Test»).listFiles() // For simple fallback values: println(files?.size ?: «empty») // if files is null, this prints «empty» // To calculate a more complicated fallback value in a code block, use `run` val filesSize = files?.size ?: run < val someSize = getSomeSize() someSize * 2 >println(filesSize)

Execute a statement if null

Get first item of a possibly empty collection

Execute if not null

Map nullable value if not null

val value = . val mapped = value?.let < transformValue(it) >?: defaultValue // defaultValue is returned if the value or the transform result is null.

Return on when statement

fun transform(color: String): Int < return when (color) < "Red" ->0 «Green» -> 1 «Blue» -> 2 else -> throw IllegalArgumentException(«Invalid color param value») > >

try-catch expression

if expression

Builder-style usage of methods that return Unit

Single-expression functions

This can be effectively combined with other idioms, leading to shorter code. For example, with the when expression:

fun transform(color: String): Int = when (color) < "Red" ->0 «Green» -> 1 «Blue» -> 2 else -> throw IllegalArgumentException(«Invalid color param value») >

Call multiple methods on an object instance (with)

Configure properties of an object (apply)

This is useful for configuring properties that aren’t present in the object constructor.

Java 7’s try-with-resources

val stream = Files.newInputStream(Paths.get(«/some/file.txt»)) stream.buffered().reader().use < reader ->println(reader.readText()) >

Generic function that requires the generic type information

// public final class Gson < // . // public T fromJson(JsonElement json, Class classOfT) throws JsonSyntaxException < // . inline fun Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)

Nullable Boolean

Swap two variables

Mark code as incomplete (TODO)

Kotlin’s standard library has a TODO() function that will always throw a NotImplementedError . Its return type is Nothing so it can be used regardless of expected type. There’s also an overload that accepts a reason parameter:

IntelliJ IDEA’s kotlin plugin understands the semantics of TODO() and automatically adds a code pointer in the TODO tool window.

What’s next?

  • Solve Advent of Code puzzles using the idiomatic Kotlin style.
  • Learn how to perform typical tasks with strings in Java and Kotlin.
  • Learn how to perform typical tasks with collections in Java and Kotlin.
  • Learn how to handle nullability in Java and Kotlin.

Источник

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