是否有可能实现一个HashMap有一个键和两个值。就像HashMap?
请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?
是否有可能实现一个HashMap有一个键和两个值。就像HashMap?
请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?
当前回答
Apache Commons集合类可以在同一个键下实现多个值。
MultiMap multiMapDemo = new MultiValueMap();
multiMapDemo .put("fruit", "Mango");
multiMapDemo .put("fruit", "Orange");
multiMapDemo.put("fruit", "Blueberry");
System.out.println(multiMapDemo.get("fruit"));
Maven的依赖
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
其他回答
看一看guava库中的Multimap及其实现——HashMultimap
类似于Map的集合,但可以将多个值与单个键关联。如果使用相同的键但不同的值调用put(K, V)两次,则multimap包含从键到两个值的映射。
可以使用identityHashMap完成,条件是键比较将由==操作符完成,而不是equals()。
不,不只是作为HashMap。你基本上需要一个HashMap,从一个键到一个值的集合。
如果你喜欢使用外部库,Guava在Multimap中就有这个概念,比如ArrayListMultimap, HashMultimap, LinkedHashMultimap等。
Multimap<String, Integer> nameToNumbers = HashMultimap.create();
System.out.println(nameToNumbers.put("Ann", 5)); // true
System.out.println(nameToNumbers.put("Ann", 5)); // false
nameToNumbers.put("Ann", 6);
nameToNumbers.put("Sam", 7);
System.out.println(nameToNumbers.size()); // 3
System.out.println(nameToNumbers.keySet().size()); // 2
你可以隐式地做。
// Create the map. There is no restriction to the size that the array String can have
HashMap<Integer, String[]> map = new HashMap<Integer, String[]>();
//initialize a key chosing the array of String you want for your values
map.put(1, new String[] { "name1", "name2" });
//edit value of a key
map.get(1)[0] = "othername";
这是非常简单和有效的。 如果你想要不同类的值,你可以这样做:
HashMap<Integer, Object[]> map = new HashMap<Integer, Object[]>();
HashMap<Integer,ArrayList<String>> map = new HashMap<Integer,ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
list.add("abc");
list.add("xyz");
map.put(100,list);