Java: Composite key in hashmaps

前端 未结 9 691
太阳男子
太阳男子 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:40

    You don't need to reinvent the wheel. Simply use the Guava's HashBasedTable implementation of Table interface, for your need. Here is an example

    Table table = HashBasedTable.create();
    
    table.put("key-1", "lock-1", 50);
    table.put("lock-1", "key-1", 100);
    
    System.out.println(table.get("key-1", "lock-1")); //prints 50
    System.out.println(table.get("lock-1", "key-1")); //prints 100
    
    table.put("key-1", "lock-1", 150); //replaces 50 with 150
    

    Happy coding!

提交回复
热议问题