Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have a composite key in Kotlin?

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>()
like image 227
fafl Avatar asked Oct 19 '17 13:10

fafl


People also ask

What is composite key give an example?

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.

What is the composite primary key?

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 ...

How do I get a key from kotlin value?

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}

What is composite key in Java?

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.


2 Answers

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 :)

like image 134
A Monad is a Monoid Avatar answered Sep 19 '22 11:09

A Monad is a Monoid


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))
like image 42
Vasily Sulatskov Avatar answered Sep 20 '22 11:09

Vasily Sulatskov