在java中如何表示pairs。map要求key是不重复的

Java 9+

In Java 9, you can simply write: Map.entry(key, value) to create an immutable pair.

Note: this method does not allow keys or values to be null. If you want to allow null values, for example, you'd want to change this to: Map.entry(key, Optional.ofNullable(value)).


Java 8+

In Java 8, you can use the more general-purpose javafx.util.Pair to create an immutable, serializable pair. This class does allow null keys and null values. (In Java 9, this class is included in the javafx.base module). EDIT: As of Java 11, JavaFX has been decoupled from the JDK, so you'd need the additional maven artifact org.openjfx:javafx-base.


Java 6+

In Java 6 and up, you can use the more verbose AbstractMap.SimpleImmutableEntry for an immutable pair, or AbstractMap.SimpleEntry for a pair whose value can be changed. These classes also allow null keys and null values, and are serializable.


Android

If you're writing for Android, just use Pair.create(key, value) to create an immutable pair.


Apache Commons

Apache Commons Lang provides the helpful Pair.of(key, value) to create an immutable, comparable, serializable pair.


Eclipse Collections

If you're using pairs that contain primitives, Eclipse Collections provides some very efficient primitive pair classes that will avoid all the inefficient auto-boxing and auto-unboxing.

For instance, you could use PrimitiveTuples.pair(int, int) to create an IntIntPair, or PrimitiveTuples.pair(float, long) to create a FloatLongPair.


Project Lombok

Using Project Lombok, you can create an immutable pair class simply by writing:

@Value
public class Pair<K, V> { K key; V value; }

Lombok will fill in the constructor, getters, equals()hashCode(), and toString() methods for you automatically in the generated bytecode. If you want a static factory method instead of a constructor, e.g., a Pair.of(k, v), simply change the annotation to: @Value(staticConstructor = "of").

转载于:https://www.cnblogs.com/yizhaoAI/p/9893575.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值