是否有可能实现一个HashMap有一个键和两个值。就像HashMap?
请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?
是否有可能实现一个HashMap有一个键和两个值。就像HashMap?
请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?
当前回答
不,不只是作为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
其他回答
我更喜欢下面的方法来存储任意数量的变量,而不必创建一个单独的类。
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
HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();
在for循环中。它将具有相同的效果,如相同的键和多个值。
是的,这通常被称为multimap。
参见:http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/Multimap.html
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库。这就是需要的解决方案。
只是为了记录,纯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作为实例。