我们是否可以用一个键和两个值来实现HashMap。就像HashMap一样?
还请告诉我(如果没有办法)通过其他任何方法来实现三个值的存储(以一个为键)的方法,对我有帮助吗?
我们是否可以用一个键和两个值来实现HashMap。就像HashMap一样?
还请告诉我(如果没有办法)通过其他任何方法来实现三个值的存储(以一个为键)的方法,对我有帮助吗?
Answers:
你可以:
Map<KeyType, List<ValueType>>
。Map<KeyType, WrapperType>
。Map<KeyType, Tuple<Value1Type, Value2Type>>
。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];
这种方法的缺点是列表未完全绑定到两个值。
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;
这种方法的缺点是您必须为所有这些非常简单的容器类编写很多样板代码。
3.使用元组
// 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;
我认为这是最好的解决方案。
4.多个地图
// 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"];
此解决方案的缺点是,两个映射之间的关联并不明显,程序错误可能会导致两个映射不同步。
Map<KeyType, Tuple<Value1Type, Value2Type>>
不,不只是一个HashMap
。您基本上需要一个HashMap
从键到值的集合。
如果您乐于使用外部库,那么Guava在Multimap
诸如ArrayListMultimap
和的实现中都有这个概念HashMultimap
。
ArrayListMultimap
自己的东西……或者只是使用a HashMap<String, List<Integer>>
或其他东西。基本上,每次添加值时,您都需要创建一个空列表。
HashMap<String, List<Integer>>
另一个不错的选择是使用来自Apache Commons的MultiValuedMap。查看页面顶部的所有已知实现类以了解专门的实现。
例:
HashMap<K, ArrayList<String>> map = new HashMap<K, ArrayList<String>>()
可以替换为
MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();
所以,
map.put(key, "A");
map.put(key, "B");
map.put(key, "C");
Collection<String> coll = map.get(key);
将导致coll
包含“ A”,“ B”和“ C”的集合。
看一下Multimap
番石榴库及其实现-HashMultimap
一个类似于Map的集合,但是可以将多个值与单个键相关联。如果使用相同的键但值不同两次调用put(K,V),则多映射将包含从键到两个值的映射。
我Map<KeyType, Object[]>
用于将多个值与Map中的键相关联。这样,我可以存储与键关联的不同类型的多个值。您必须通过保持正确的从Object []插入和检索的顺序来保重。
示例:考虑,我们要存储学生信息。密钥是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];
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);
仅作记录,纯JDK8解决方案将使用Map::compute
方法:
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
请注意,以确保一致的情况下多线程访问这个数据结构,ConcurrentHashMap
以及CopyOnWriteArrayList
例如需要使用。
computeIfAbsent
。map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
如果您使用Spring Framework。有:org.springframework.util.MultiValueMap
。
要创建不可修改的多值地图:
Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);
或使用 org.springframework.util.LinkedMultiValueMap
最简单的方法是使用Google收藏库:
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
}
}
Maven链接:https : //mvnrepository.com/artifact/com.google.collections/google-collections/1.0-rc2
有关更多信息,请访问:http : //tomjefferys.blogspot.be/2011/09/multimaps-google-guava.html
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
喜欢
HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();
在你的for
循环中。它将具有与相同的键和多个值相同的效果。
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库。这是必需的解决方案。
您可以隐式地进行操作。
// 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[]>();
我习惯在Objective C中使用数据字典来执行此操作。要在Java for Android中获得相似的结果更加困难。我最终创建了一个自定义类,然后仅对我的自定义类进行了哈希映射。
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;
}
}
我们可以创建一个具有多个键或值的类,并且该类的对象可用作map中的参数。您可以参考https://stackoverflow.com/a/44181931/8065321
使用Java收集器
// Group employees by department
Map<Department, List<Employee>> byDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
部门是您的关键
尝试LinkedHashMap,示例:
Map<String,String> map = new LinkedHashMap<String,String>();
map.put('1','linked');map.put('1','hash');
map.put('2','map');map.put('3','java');..
输出:
按键:1,1,2,3
值:链接,哈希,映射,java
linked
将不再存在于地图中,因为您已将其替换为hash
。