是否有可能实现一个HashMap有一个键和两个值。就像HashMap?

请帮助我,也通过告诉(如果没有办法)任何其他方法来实现三个值的存储与一个作为关键?


当前回答

 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库。这就是需要的解决方案。

其他回答

是的,这通常被称为multimap。

参见:http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/Multimap.html

我无法回复Paul的评论,所以我在这里为Vidhya创建了新的评论:

Wrapper将是我们想要存储为值的两个类的超类。

在包装器类内部,我们可以将这些关联作为两个类对象的实例变量对象。

e.g.

class MyWrapper {

 Class1 class1obj = new Class1();
 Class2 class2obj = new Class2();
...
}

在HashMap中,我们可以这样写,

Map<KeyObject, WrapperObject> 

WrapperObj将有类变量:class1Obj, class2Obj

你可以隐式地做。

// 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[]>();

只是为了记录,纯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作为实例。

看一看guava库中的Multimap及其实现——HashMultimap

类似于Map的集合,但可以将多个值与单个键关联。如果使用相同的键但不同的值调用put(K, V)两次,则multimap包含从键到两个值的映射。