Java 在同一个键下具有多个值的HashMap
我们是否可以用一个键和两个值实现一个HashMap。就像HashMap一样Java 在同一个键下具有多个值的HashMap,java,Java,我们是否可以用一个键和两个值实现一个HashMap。就像HashMap一样 请帮助我,告诉我(如果没有办法)实现三个值存储的其他方法,其中一个作为键?否,而不仅仅是作为HashMap。您基本上需要一个从键到值集合的HashMap 如果您乐于使用外部库,那么在诸如等的实现中就有了这个概念 Multimap nameToNumbers=HashMultimap.create(); System.out.println(nameToNumbers.put(“Ann”,5));//真的 System.o
请帮助我,告诉我(如果没有办法)实现三个值存储的其他方法,其中一个作为键?否,而不仅仅是作为
HashMap
。您基本上需要一个从键到值集合的HashMap
如果您乐于使用外部库,那么在诸如等的实现中就有了这个概念
Multimap nameToNumbers=HashMultimap.create();
System.out.println(nameToNumbers.put(“Ann”,5));//真的
System.out.println(nameToNumbers.put(“Ann”,5));//假的
姓名编号。把(“安”,6);
姓名编号。放入(“Sam”,7);
System.out.println(nameToNumbers.size());//3.
System.out.println(nameToNumbers.keySet().size());//2.
是和否。解决方案是为您的值构建一个包装clas,其中包含与您的键对应的2(3或更多)个值。您可以:
例子 1。以列表作为值的映射
// create our map
Map<String, List<Person>> peopleByForename = new HashMap<>();
// populate it
List<Person> people = new ArrayList<>();
people.add(new Person("Bob Smith"));
people.add(new Person("Bob Jones"));
peopleByForename.put("Bob", people);
// read from it
List<Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs[0];
Person bob2 = bobs[1];
// you'll have to write or download a Tuple class in Java, (.NET ships with one)
// create our map
Map<String, Tuple2<Person, Person> peopleByForename = new HashMap<>();
// populate it
peopleByForename.put("Bob", new Tuple2(new Person("Bob Smith",
new Person("Bob Jones"));
// read from it
Tuple<Person, Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs.Item1;
Person bob2 = bobs.Item2;
//创建我们的地图
MappeopleByForeName=新HashMap();
//填充它
List people=new ArrayList();
添加(新人物(“Bob Smith”);
添加(新人物(“鲍勃·琼斯”);
peopleByForename.put(“Bob”,people);
//从中读出
列出Bob=peopleByForename[“Bob”];
人员bob1=bobs[0];
人员bob2=bobs[1];
这种方法的缺点是列表不能精确地绑定到两个值
2。使用包装类
// define our wrapper
class Wrapper {
public Wrapper(Person person1, Person person2) {
this.person1 = person1;
this.person2 = person2;
}
public Person getPerson1 { return this.person1; }
public Person getPerson2 { return this.person2; }
private Person person1;
private Person person2;
}
// create our map
Map<String, Wrapper> peopleByForename = new HashMap<>();
// populate it
Wrapper people = new Wrapper();
peopleByForename.put("Bob", new Wrapper(new Person("Bob Smith"),
new Person("Bob Jones"));
// read from it
Wrapper bobs = peopleByForename.get("Bob");
Person bob1 = bobs.getPerson1;
Person bob2 = bobs.getPerson2;
// create our maps
Map<String, Person> firstPersonByForename = new HashMap<>();
Map<String, Person> secondPersonByForename = new HashMap<>();
// populate them
firstPersonByForename.put("Bob", new Person("Bob Smith"));
secondPersonByForename.put("Bob", new Person("Bob Jones"));
// read from them
Person bob1 = firstPersonByForename["Bob"];
Person bob2 = secondPersonByForename["Bob"];
//定义我们的包装器
类包装器{
公共包装(人员1、人员2){
this.person1=person1;
this.person2=person2;
}
公众人物getPerson1{返回this.person1;}
公众人物getPerson2{返回this.person2;}
私人1;
私人2;
}
//创建我们的地图
MappeopleByForeName=新HashMap();
//填充它
包装人=新包装人();
peopleByForename.put(“鲍勃”),new Wrapper(新人(“鲍勃·史密斯”),
新人(“鲍勃·琼斯”);
//从中读出
包装器bobs=peopleByForename.get(“Bob”);
人员bob1=bobs.getPerson1;
Person bob2=bobs.getPerson2;
这种方法的缺点是必须为所有这些非常简单的容器类编写大量的boiler plate代码
3.使用元组
// create our map
Map<String, List<Person>> peopleByForename = new HashMap<>();
// populate it
List<Person> people = new ArrayList<>();
people.add(new Person("Bob Smith"));
people.add(new Person("Bob Jones"));
peopleByForename.put("Bob", people);
// read from it
List<Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs[0];
Person bob2 = bobs[1];
// you'll have to write or download a Tuple class in Java, (.NET ships with one)
// create our map
Map<String, Tuple2<Person, Person> peopleByForename = new HashMap<>();
// populate it
peopleByForename.put("Bob", new Tuple2(new Person("Bob Smith",
new Person("Bob Jones"));
// read from it
Tuple<Person, Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs.Item1;
Person bob2 = bobs.Item2;
//您必须用Java编写或下载一个元组类,(.NET附带一个元组类)
//创建我们的地图
映射是的,这通常被称为多重映射
请参阅:查看来自guava库的Multimap
及其实现-
一种类似于映射的集合,但可能将多个值与单个键关联。如果使用相同的键但不同的值调用put(K,V)两次,则多映射包含从键到两个值的映射
我无法回复Paul的评论,因此我在这里为Vidhya创建了新的评论:
对于我们要存储为值的两个类,包装器将是一个超类
在包装类内部,我们可以将关联作为两个类对象的实例变量对象
e、 g
在HashMap中,我们可以用这种方式
Map<KeyObject, WrapperObject>
Map
WrapperObj将有类变量:classaobj,class2Obj
另一个不错的选择是从Apache Commons使用。查看页面顶部的所有已知实现类,了解专门的实现
例如:
HashMap<K, ArrayList<String>> map = new HashMap<K, ArrayList<String>>()
HashMap=newhashmap()
可以用
MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();
MultiValuedMap map=新的MultiValuedHashMap();
所以
map.put(键“A”);
地图放置(键“B”);
地图放置(键“C”);
Collection coll=map.get(键);
将导致集合coll
包含“A”、“B”和“C”。我使用Map
将多个值与映射中的键关联。这样,我可以存储与键关联的多个不同类型的值。您必须注意保持从对象[]插入和检索的正确顺序
例如:
考虑到,我们想存储学生信息。KEY是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];
//进入地图
Map studenMap=newhashmap();
String[]studentInformationArray=新字符串[]{“姓名”、“地址”、“电子邮件”};
int studenId=1;
studenMap.put(studenId,studentInformation数组);
//从映射中检索值的步骤
String name=studenMap.get(studenId)[1];
字符串地址=studenMap.get(studenId)[2];
字符串email=studenMap.get(studenId)[3];
HashMap map=newhashmap();
ArrayList=新建ArrayList();
列表。添加(“abc”);
列表。添加(“xyz”);
地图放置(100,列表);
您可以隐式执行
// 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=newHashMap();
//初始化一个键,选择值所需的字符串数组
put(1,新字符串[]{“name1”,“name2”});
//编辑键的值
map.get(1)[0]=“其他名称”;
这是非常简单和有效的。
如果需要不同类的值,可以执行以下操作:
HashMap<Integer, Object[]> map = new HashMap<Integer, Object[]>();
HashMap map=newhashmap();
为了记录在案,纯JDK8解决方案将使用Map::compute
方法:
map.compute(key, (s, strings) -> strings == null ? new ArrayList<>() : strings).add(value);
请注意,为了确保多线程访问此数据结构时的一致性,ConcurrentHashMap
和Copy
HashMap<Integer, Object[]> map = new HashMap<Integer, Object[]>();
map.compute(key, (s, strings) -> strings == null ? new ArrayList<>() : strings).add(value);
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<>();
put(map, "first", "hello");
put(map, "first", "foo");
put(map, "bar", "foo");
put(map, "first", "hello");
map.forEach((s, strings) -> {
System.out.print(s + ": ");
System.out.println(strings.stream().collect(Collectors.joining(", ")));
});
}
private static <KEY, VALUE> void put(Map<KEY, List<VALUE>> map, KEY key, VALUE value) {
map.compute(key, (s, strings) -> strings == null ? new ArrayList<>() : strings).add(value);
}
bar: foo
first: hello, foo, hello
final public static Map<String, Map<String, Float>> myMap = new HashMap<String, Map<String, Float>>();
String key= "services_servicename"
ArrayList<String> data;
for(int i = 0; i lessthen data.size(); i++) {
HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();
servicesNameHashmap.put(key,data.get(i).getServiceName());
mServiceNameArray.add(i,servicesNameHashmap);
}
HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();
public class Test1 {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addview);
//create the datastring
HashMap<Integer, myClass> hm = new HashMap<Integer, myClass>();
hm.put(1, new myClass("Car", "Small", 3000));
hm.put(2, new myClass("Truck", "Large", 4000));
hm.put(3, new myClass("Motorcycle", "Small", 1000));
//pull the datastring back for a specific item.
//also can edit the data using the set methods. this just shows getting it for display.
myClass test1 = hm.get(1);
String testitem = test1.getItem();
int testprice = test1.getPrice();
Log.i("Class Info Example",testitem+Integer.toString(testprice));
}
}
//custom class. You could make it public to use on several activities, or just include in the activity if using only here
class myClass{
private String item;
private String type;
private int price;
public myClass(String itm, String ty, int pr){
this.item = itm;
this.price = pr;
this.type = ty;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getType() {
return item;
}
public void setType(String type) {
this.type = type;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class Test {
public static void main(final String[] args) {
// multimap can handle one key with a list of values
final Multimap<String, String> cars = ArrayListMultimap.create();
cars.put("Nissan", "Qashqai");
cars.put("Nissan", "Juke");
cars.put("Bmw", "M3");
cars.put("Bmw", "330E");
cars.put("Bmw", "X6");
cars.put("Bmw", "X5");
cars.get("Bmw").forEach(System.out::println);
// It will print the:
// M3
// 330E
// X6
// X5
}
}
Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);
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"]
MultiMap multiMapDemo = new MultiValueMap();
multiMapDemo .put("fruit", "Mango");
multiMapDemo .put("fruit", "Orange");
multiMapDemo.put("fruit", "Blueberry");
System.out.println(multiMapDemo.get("fruit"));
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>