是否有可能实现一个HashMap有一个键和两个值。就像HashMap?

请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?


当前回答

我更喜欢下面的方法来存储任意数量的变量,而不必创建一个单独的类。

final public static Map<String, Map<String, Float>> myMap    = new HashMap<String, Map<String, Float>>();

其他回答

使用Java收集器

// Group employees by department
Map<Department, List<Employee>> byDept = employees.stream()
                    .collect(Collectors.groupingBy(Employee::getDepartment));

你的钥匙在哪个部门

不,不只是作为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

是的,这通常被称为multimap。

参见:http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/Multimap.html

你可以隐式地做。

// 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[]>();

是也不是。解决方案是为包含与键对应的2(3或更多)值的值构建一个Wrapper类。