是否有可能实现一个HashMap有一个键和两个值。就像HashMap?
请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?
是否有可能实现一个HashMap有一个键和两个值。就像HashMap?
请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?
当前回答
我使用Map<KeyType, Object[]>将多个值与Map中的一个键关联起来。这样,我就可以存储与一个键关联的多个不同类型的值。你必须注意保持正确的插入和从Object[]中检索的顺序。
例子: 考虑一下,我们想要存储Student信息。键是id,而我们想要存储姓名,地址和电子邮件与学生相关联。
//To make entry into Map
Map<Integer, String[]> studenMap = new HashMap<Integer, String[]>();
String[] studentInformationArray = new String[]{"name", "address", "email"};
int studenId = 1;
studenMap.put(studenId, studentInformationArray);
//To retrieve values from Map
String name = studenMap.get(studenId)[1];
String address = studenMap.get(studenId)[2];
String email = studenMap.get(studenId)[3];
其他回答
我无法回复Paul的评论,所以我在这里为Vidhya创建了新的评论:
Wrapper将是我们想要存储为值的两个类的超类。
在包装器类内部,我们可以将这些关联作为两个类对象的实例变量对象。
e.g.
class MyWrapper {
Class1 class1obj = new Class1();
Class2 class2obj = new Class2();
...
}
在HashMap中,我们可以这样写,
Map<KeyObject, WrapperObject>
WrapperObj将有类变量:class1Obj, class2Obj
如果你使用Spring Framework。有:org.springframework.util.MultiValueMap。
创建不可修改的多值映射:
Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);
或者使用org.springframework.util.LinkedMultiValueMap
可以使用identityHashMap完成,条件是键比较将由==操作符完成,而不是equals()。
使用Java收集器
// Group employees by department
Map<Department, List<Employee>> byDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
你的钥匙在哪个部门
我使用Map<KeyType, Object[]>将多个值与Map中的一个键关联起来。这样,我就可以存储与一个键关联的多个不同类型的值。你必须注意保持正确的插入和从Object[]中检索的顺序。
例子: 考虑一下,我们想要存储Student信息。键是id,而我们想要存储姓名,地址和电子邮件与学生相关联。
//To make entry into Map
Map<Integer, String[]> studenMap = new HashMap<Integer, String[]>();
String[] studentInformationArray = new String[]{"name", "address", "email"};
int studenId = 1;
studenMap.put(studenId, studentInformationArray);
//To retrieve values from Map
String name = studenMap.get(studenId)[1];
String address = studenMap.get(studenId)[2];
String email = studenMap.get(studenId)[3];