当前位置:网站首页>On map state mapping
On map state mapping
2022-06-22 02:56:00 【Your baby】
List of articles
1 Problem description
Recently at work , There are many places in the project that need to be used Map To do state mapping .
The characteristic of this state mapping is , A build , Unlimited use , No more changes .
So here comes the question , stay Java in , establish Map , And fill in key value pairs , It is a tedious and repetitive work .
For example, express the following mapping relationship :
{
1={
1=SF, 2=YT, 3=JD}
}
Use Java The implementation needs to be written like this :
Map<Integer, Map<Integer, String>> maps = new HashMap<>();
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, "SF");
map1.put(2, "YT");
map1.put(3, "JD");
maps.put(1, map1);
So if in this process , There are many state mappings , have to new quite a lot map, have to put Many times . This article will talk about this problem .
2 Problem solving
2.1 JAVA 9 in Of Map Realization
stay Map Interface defines many overloaded of Method , among 2 The method of key value pairs is as follows :
static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2) {
return new ImmutableCollections.MapN<>(k1, v1, k2, v2);
}
in other words , When use , Can directly Map.of(), Then pass in parameters to build what you want Map example .Java 9 Provides 10 Give us the key value pairs , Can meet most of the needs .
2.2 Hutool Dictionary class in
Please refer to :
https://www.hutool.cn/docs/#/core/%E8%AF%AD%E8%A8%80%E7%89%B9%E6%80%A7/HashMap%E6%89%A9%E5%B1%95-Dict
2.3 Make your own wheels
Here is a simple demo.
2.3.1 One demo
package org.feng;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class MapDemo {
private static final MapDemo DEMO = new MapDemo();
/** * Parameter description :k1,v1,k2,v2,k3,v3... */
public static Map<Integer, String> intStringMap(Object... objects) {
return DEMO.of(objects);
}
/** * Parameter description :k1,v1,k2,v2,k3,v3... */
public static Map<String, Object> stringObjectMap(Object... objects) {
return DEMO.of(objects);
}
@SuppressWarnings("unchecked")
public final <K, V> Map<K, V> of(Object... object) {
int length = object.length;
// The length should be even
if ((length & 1) != 0) {
throw new IllegalArgumentException(" Incorrect number of parameters ");
}
// size = length / 2
int size = length >> 1;
SimpleEntry<K, V>[] entry = new SimpleEntry[size];
for (int i = 0, j = 0; i < object.length - 1; i += 2) {
entry[j++] = new SimpleEntry<>((K) object[i], (V) object[i + 1]);
}
return ofEntry(entry);
}
@SafeVarargs
public final <K, V> Map<K, V> ofEntry(SimpleEntry<K, V>... entries) {
if (entries.length == 0) {
return new HashMap<>(16);
}
Map<K, V> instance = new HashMap<>(16);
for (SimpleEntry<K, V> entry : entries) {
instance.put(entry.key, entry.value);
}
return instance;
}
private static class SimpleEntry<K, V> implements Map.Entry<K, V> {
private final K key;
private final V value;
public SimpleEntry(K key, V value) {
this.key = key;
this.value = value;
}
/** * Returns the key corresponding to this entry. * * @return the key corresponding to this entry * @throws IllegalStateException implementations may, but are not * required to, throw this exception if the entry has been * removed from the backing map. */
@Override
public K getKey() {
return this.key;
}
/** * Returns the value corresponding to this entry. If the mapping * has been removed from the backing map (by the iterator's * {@code remove} operation), the results of this call are undefined. * * @return the value corresponding to this entry * @throws IllegalStateException implementations may, but are not * required to, throw this exception if the entry has been * removed from the backing map. */
@Override
public V getValue() {
return this.value;
}
/** * Replaces the value corresponding to this entry with the specified * value (optional operation). (Writes through to the map.) The * behavior of this call is undefined if the mapping has already been * removed from the map (by the iterator's {@code remove} operation). * * @param value new value to be stored in this entry * @return old value corresponding to the entry * @throws UnsupportedOperationException if the {@code put} operation * is not supported by the backing map * @throws ClassCastException if the class of the specified value * prevents it from being stored in the backing map * @throws NullPointerException if the backing map does not permit * null values, and the specified value is null * @throws IllegalArgumentException if some property of this value * prevents it from being stored in the backing map * @throws IllegalStateException implementations may, but are not * required to, throw this exception if the entry has been * removed from the backing map. */
@Override
public V setValue(Object value) {
throw new UnsupportedOperationException("SimpleEntry It is not allowed to modify the value ");
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SimpleEntry<?, ?> that = (SimpleEntry<?, ?>) o;
return Objects.equals(key, that.key) && Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
@Override
public String toString() {
return getKey() + "=" + getValue();
}
}
}
2.3.2 Test use
Use main Method calls the above demo.
public static void main(String[] args) {
System.out.println(intStringMap(1, "SF", 2, "YT", 3, "HT"));
System.out.println(stringObjectMap("1", "SF", "2", "YT", "3", "HT", 1, "HH"));
}
The console output is as follows :
{
1=SF, 2=YT, 3=HT}
{
1=SF, 1=HH, 2=YT, 3=HT}
2.3.3 matters needing attention
Above demo in , Use directly inside new HashMap The way , External input parameters are used (k1,v1,k2,v2…) The way , The actual use is a Object Infinite arguments to type .
therefore , When building the mapping , The specific type of the parameter cannot be determined . Users need to know what scenarios this class is used in , It is equivalent to an agreement .
{
1=SF, 2=YT, 3=HT}
{
1=SF, 1=HH, 2=YT, 3=HT}
2.3.3 matters needing attention
Above demo in , Use directly inside new HashMap The way , External input parameters are used (k1,v1,k2,v2…) The way , The actual use is a Object Infinite arguments to type .
therefore , When building the mapping , The specific type of the parameter cannot be determined . Users need to know what scenarios this class is used in , It is equivalent to an agreement .
PS: If you have a better idea , You can leave a message , We improve together .
边栏推荐
- 银联支付 返回商户 Nignx post请求405
- C mapster object mapper learning
- Figure base de données ongdb version V - 1.0.2
- Unity3d post process volume profile
- 微软 IE 浏览器于 6 月 15 日被永久关闭
- Architecture and practice of vivo container cluster monitoring system
- xpm_memory_tdpram原语的完整使用实例
- Flink CDC MongoDB Connector 的实现原理和使用实践
- Kubernetes code generator use
- ZCMU--1052: Holedox Eating(C语言)
猜你喜欢

GraphConnect 2022 大会的产品发布一览

【一起上水硕系列】Day Two

Li Kou today's question 1108 IP address invalidation

Brief analysis of application source code of neo4j intelligent supply chain

Flink CDC MongoDB Connector 的实现原理和使用实践

Select for i/0 multiplexing

How to select the appropriate version of neo4j (version 2022)

图数据平台解决方案:单节点部署
![[2. merge sort]](/img/60/5e87cffabd91af0155ae681f5bf0ba.png)
[2. merge sort]

【4. 高精度加法】
随机推荐
Must the database primary key be self incremented? What scenarios do not suggest self augmentation?
Sword finger offer 58 Symmetric binary tree
Select for i/0 multiplexing
Is the link of Hengtai securities VIP low commission account opening safe?
table标签的不规则布局
Day20qt multiple forms switching idea 2021-10-31
【7. 高精度除法】
Implementation differences between import and require in browser and node environments
ModuleNotFoundError: No module named ‘torchvision. datasets‘; ‘ torchvision‘ is not a package
How to use tensorboard add_ histogram
最新發布:Neo4j 圖數據科學 GDS 2.0 和 AuraDS GA
Force buckle 160 Intersecting linked list
Neo4j 技能树正式发布,助你轻松掌握Neo4j图数据库
Latest release: neo4j figure data science GDS 2.0 and aurads GA
Figure base de données ongdb version V - 1.0.2
Sword finger offer 12 Path in matrix
C ++ Primer 第2章 变量和基本类型 总结
Two dot vertical progress styles
圖數據庫ONgDB Release v-1.0.2
GraphAcademy 课程讲解:《Neo4j 图数据科学基础》