是否有可能实现一个HashMap有一个键和两个值。就像HashMap?
请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?
是否有可能实现一个HashMap有一个键和两个值。就像HashMap?
请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?
当前回答
是也不是。解决方案是为包含与键对应的2(3或更多)值的值构建一个Wrapper类。
其他回答
你可以隐式地做。
// 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[]>();
import java.io.*;
import java.util.*;
import com.google.common.collect.*;
class finTech{
public static void main(String args[]){
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("1","11");
multimap.put("1","14");
multimap.put("1","12");
multimap.put("1","13");
multimap.put("11","111");
multimap.put("12","121");
System.out.println(multimap);
System.out.println(multimap.get("11"));
}
}
输出:
{"1"=["11","12","13","14"],"11"=["111"],"12"=["121"]}
["111"]
这是用于实用功能的Google-Guava库。这就是需要的解决方案。
我们可以创建一个类来拥有多个键或值,该类的对象可以用作map中的参数。 你可以参考https://stackoverflow.com/a/44181931/8065321
使用Java收集器
// Group employees by department
Map<Department, List<Employee>> byDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
你的钥匙在哪个部门
我无法回复Paul的评论,所以我在这里为Vidhya创建了新的评论:
Wrapper将是我们想要存储为值的两个类的超类。
在包装器类内部,我们可以将这些关联作为两个类对象的实例变量对象。
e.g.
class MyWrapper {
Class1 class1obj = new Class1();
Class2 class2obj = new Class2();
...
}
在HashMap中,我们可以这样写,
Map<KeyObject, WrapperObject>
WrapperObj将有类变量:class1Obj, class2Obj