In Python i can have complex dictionary keys like for example:
d = {}
d[(1, 2)] = 3
print d[(1, 2)] # prints 3
How can I declare and populate such a Map in Kotlin?
Edit: I tried to declare a Map like this, but I don't know how to populate it:
val my_map = HashMap<Pair<Int, Int>, Int>()
A composite key, then, would be the combination of two keys. For example: the combination of house number and street might qualify as a composite key, given that the market listings are local. If so, then when someone searches using both the house number and the street, they should only get one single record returned.
A Composite Primary Key is created by combining two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined, but it does not guarantee uniqueness when taken individually, or it can also be understood as a primary key created by combining two or more ...
Kotlin HashMap get key by value We can find all keys that are paired with a given value using filterValues() method and Map's keys property. For example, there are 2 entries with value = 9999 in the HashMap: {“zkoder”, 9999}
A composite primary key, also called a composite key, is a combination of two or more columns to form a primary key for a table. In JPA, we have two options to define the composite keys: the @IdClass and @EmbeddedId annotations.
It's simple, you first create your dictionary and then insert the key and values:
val (a, b):Pair<Int, String> = Pair(1, "x")
val map: HashMap<Pair<Int, String>, Int> = hashMapOf((a, b) to 1)
map[Pair(2, "y")] = 3
and so on :)
In Kotlin, unlike Python there's no tuple data type. For two-tuples there's a Pair class. For larger arity you are supposed to use data classes.
val map: HashMap<Pair<Int, Int>, Int> = hashMapOf(Pair(1, 2) to 3)
val nullable: Int? = map[Pair(1, 2)]
val notNullable = map.getValue(Pair(1, 2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With