当前位置:网站首页>On map state mapping

On map state mapping

2022-06-22 02:56:00 Your baby

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 .

原网站

版权声明
本文为[Your baby]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220252244305.html