是否有可能实现一个HashMap有一个键和两个值。就像HashMap?
请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?
是否有可能实现一个HashMap有一个键和两个值。就像HashMap?
请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?
当前回答
只是为了记录,纯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作为实例。
其他回答
不,不只是作为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
Apache Commons集合类可以在同一个键下实现多个值。
MultiMap multiMapDemo = new MultiValueMap();
multiMapDemo .put("fruit", "Mango");
multiMapDemo .put("fruit", "Orange");
multiMapDemo.put("fruit", "Blueberry");
System.out.println(multiMapDemo.get("fruit"));
Maven的依赖
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
我无法回复Paul的评论,所以我在这里为Vidhya创建了新的评论:
Wrapper将是我们想要存储为值的两个类的超类。
在包装器类内部,我们可以将这些关联作为两个类对象的实例变量对象。
e.g.
class MyWrapper {
Class1 class1obj = new Class1();
Class2 class2obj = new Class2();
...
}
在HashMap中,我们可以这样写,
Map<KeyObject, WrapperObject>
WrapperObj将有类变量:class1Obj, class2Obj
我更喜欢下面的方法来存储任意数量的变量,而不必创建一个单独的类。
final public static Map<String, Map<String, Float>> myMap = new HashMap<String, Map<String, Float>>();
我们可以创建一个类来拥有多个键或值,该类的对象可以用作map中的参数。 你可以参考https://stackoverflow.com/a/44181931/8065321