Java: Composite key in hashmaps

前端 未结 9 680
太阳男子
太阳男子 2020-12-24 12:53

I would like to store a group of objects in a hashmap , where the key shall be a composite of two string values. is there a way to achieve this?

i can simply concate

9条回答
  •  春和景丽
    2020-12-24 13:35

    public static String fakeMapKey(final String... arrayKey) {
        String[] keys = arrayKey;
    
        if (keys == null || keys.length == 0)
            return null;
    
        if (keys.length == 1)
            return keys[0];
    
        String key = "";
        for (int i = 0; i < keys.length; i++)
            key += "{" + i + "}" + (i == keys.length - 1 ? "" : "{" + keys.length + "}");
    
        keys = Arrays.copyOf(keys, keys.length + 1);
    
        keys[keys.length - 1] = FAKE_KEY_SEPARATOR;
    
        return  MessageFormat.format(key, (Object[]) keys);}
    
    public static string FAKE_KEY_SEPARATOR = "~";
    
    INPUT: fakeMapKey("keyPart1","keyPart2","keyPart3");
    OUTPUT: keyPart1~keyPart2~keyPart3

提交回复
热议问题