What is the best practice for creating a single key value object in java? I know there is: Object, Pair, Map.Entry , KeyValue. For a simple KV use such as {"name":"coolName"} what should i use?
The most standard way to represent a key-value pair is with Map.Entry:
A map entry (key-value pair).
This is better than the others you suggest because:
Object: has no notion of it having any meaningful structurePair: better, but does not semantically convey that the first thing is a key and the second is a value.KeyValue: don't know what this is, but I don't think it's part of the standard SDK.Map.Entry is in java.util, so it's available everywhere.
You can create an instance using:
new AbstractMap.SimpleEntry<>(key, value)
As pointed out by Michael, Java 9 adds a helper method:
Map.entry(key, value)
You can use Pair<K,V> (implementation of Map.Entry<K,V> from commons-lang3) and the relevant method in Java 11: Map.entry.
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