Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice for KV object in java?

Tags:

java

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?

like image 237
Tomer Avatar asked Nov 27 '25 18:11

Tomer


2 Answers

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 structure
  • Pair: 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)
like image 199
Andy Turner Avatar answered Dec 01 '25 23:12

Andy Turner


You can use Pair<K,V> (implementation of Map.Entry<K,V> from commons-lang3) and the relevant method in Java 11: Map.entry.

like image 32
NoDataFound Avatar answered Dec 01 '25 23:12

NoDataFound



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!