HashMap:一键多值


72

如何获得此映射中第一个键的第三个值?这可能吗?


我可以通过使用HashMap :: get的成员函数来获取键的第一个值,尽管第三个是?我找不到任何代码。
防晒霜

2
您找不到自己的代码吗?那就是他在说的。
Bhesh Gurung

1
听起来您可能对键和哈希键之间的区别有些困惑。希望这能使您直截了当:en.wikipedia.org/wiki/Hashmap
vaughandroid

4
一张地图不能为一个键具有多个值,但是您可以将Collection作为值
Nathan Q

Answers:


92

存在执行此操作的库,但是最简单的普通Java方法是创建如下所示的Mapof List

Map<Object,ArrayList<Object>> multiMap = new HashMap<>();

9
从键盘上转5秒钟,然后响起...别人发布的相同答案。+1
Newtopian 2011年

4
但是,使用库可能比滚动自己的库,测试它等更简单……
Jon Skeet

仅当ArrayList中的对象来自相同类型时,此解决方案才有效。S,fe,不可能有一个带有int和双
精度

@JonSkeet是此用例的推荐库?
拉夫

1
@gaurav:自从我进入Java世界以来已经很久了,我不想说。我会看看番石榴。
乔恩·斯基特

31

听起来您正在寻找多图Guava具有各种Multimap实现,通常是通过Multimaps类创建的。

我建议使用该实现可能比滚动自己的实现更简单,确定API的外观,在添加值时仔细检查现有列表等。如果您的情况对第三方库有特定的厌恶,也许值得这样做,但否则Guava是一个很棒的库,它也可能会帮助您使用其他代码:)


Apache Commons Collections也具有Multimap实现。
罗伯特

Apache Commons MultiMap的
Joarder Kamal

大声笑两个坏链接。
GC_

@GC_:是的,该职位将近9年了。那个会发生。轻松修复,无需“大声笑”。(或者您是说Apache公地的??在这种情况下,我笑着说,与其说笑,不如说是更具建设性的回应,即发布新链接:MultiMap
Jon Skeet

23

例如:

Map<Object,Pair<Integer,String>> multiMap = new HashMap<Object,Pair<Integer,String>>();

其中Pair是参数类

public class Pair<A, B> {
    A first = null;
    B second = null;

    Pair(A first, B second) {
        this.first = first;
        this.second = second;
    }

    public A getFirst() {
        return first;
    }

    public void setFirst(A first) {
        this.first = first;
    }

    public B getSecond() {
        return second;
    }

    public void setSecond(B second) {
        this.second = second;
    }

}

12

这是我在类似问题的答案中发现的

Map<String, List<String>> hm = new HashMap<String, List<String>>();
List<String> values = new ArrayList<String>();
values.add("Value 1");
values.add("Value 2");
hm.put("Key1", values);

// to get the arraylist
System.out.println(hm.get("key1"));

结果:[值1,值2]


System.out.println(hm.get(“ Key1”));
Snow Bases'Nov

10

你有这样的东西吗?

HashMap<String, ArrayList<String>>

如果是这样,则可以遍历ArrayList并使用arrayList.get(i)获得所需的项目。


3
如何将元素添加到arraylist并进行迭代
user3504024


7

我在随机搜索中找到了该博客,我认为这样做会有所帮助:http : //tomjefferys.blogspot.com.tr/2011/09/multimaps-google-guava.html

public class MutliMapTest {
public static void main(String... args) {
   Multimap<String, String> myMultimap = ArrayListMultimap.create();

   // Adding some key/value
   myMultimap.put("Fruits", "Bannana");
   myMultimap.put("Fruits", "Apple");
   myMultimap.put("Fruits", "Pear");
   myMultimap.put("Vegetables", "Carrot");

   // Getting the size
   int size = myMultimap.size();
   System.out.println(size);  // 4

   // Getting values
   Collection<String> fruits = myMultimap.get("Fruits");
   System.out.println(fruits); // [Bannana, Apple, Pear]

   Collection<string> vegetables = myMultimap.get("Vegetables");
   System.out.println(vegetables); // [Carrot]

   // Iterating over entire Mutlimap
   for(String value : myMultimap.values()) {
      System.out.println(value);
   }

   // Removing a single value
   myMultimap.remove("Fruits","Pear");
   System.out.println(myMultimap.get("Fruits")); // [Bannana, Pear]

   // Remove all values for a key
   myMultimap.removeAll("Fruits");
   System.out.println(myMultimap.get("Fruits")); // [] (Empty Collection!)
}
}

最好和最简单的感谢ozan。谢谢番石榴。
阿卜杜拉

5

尝试使用集合来存储键的值:

Map<Key, Collection<Value>>

您必须自己维护值列表


1

解决方案是Apache Commons集合类。

    MultiMap multiMapDemo = new MultiValueMap();

    multiMapDemo .put("fruit", "Mango");
    multiMapDemo .put("fruit", "Orange");
    multiMapDemo.put("fruit", "Blueberry");

    System.out.println(multiMap.get("fruit"));
   // Mango Orange Blueberry

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>

0

考虑一下带有2个键的Map,立即使我不得不使用用户定义的键,这可能是一个Class。以下是关键类:

public class MapKey {
    private Object key1;
    private Object key2;

    public Object getKey1() {
        return key1;
    }

    public void setKey1(Object key1) {
        this.key1 = key1;
    }

    public Object getKey2() {
        return key2;
    }

    public void setKey2(Object key2) {
        this.key2 = key2;
    }
}


// Create first map entry with key <A,B>.
        MapKey mapKey1 = new MapKey();
        mapKey1.setKey1("A");
        mapKey1.setKey2("B");

0

HashMap –使用列表的单键和多个值

Map<String, List<String>> map = new HashMap<String, List<String>>();

  // create list one and store values

    List<String> One = new ArrayList<String>();
    One.add("Apple");
    One.add("Aeroplane");

    // create list two and store values
    List<String> Two = new ArrayList<String>();
    Two.add("Bat");
    Two.add("Banana");

    // put values into map
    map.put("A", One);
    map.put("B", Two);
    map.put("C", Three);

0

您可以执行以下操作(根据需要添加访问修饰符):

Map<String,Map<String,String>> complexMap=new HashMap<String,Map<String,String>>();

您可以像这样插入数据:

    Map<String,String> componentMap = new HashMap<String,String>();
    componentMap.put("foo","bar");
    componentMap.put("secondFoo","secondBar");
    complexMap.put("superFoo",componentMap);

生成的数据结构将是:

{superFoo={secondFoo=secondBar, foo=bar}}

这样,键的每个值都应具有唯一的标识符。如果密钥已知,还给出O(1)进行提取。


那么如何设置数据呢?
赛卡特

@SaikatBarua对延迟的回复感到抱歉。请检查更新后的答案。
thedeadalive

0

编写一个新类,其中包含所需的所有值,并将新类的对象用作HashMap中的值

HashMap<String, MyObject>

class MyObject {
public String value1;
public int value2;
public List<String> value3;
}

0

这是代码如何将哈希图提取到数组中,该哈希图包含arraylist

Map<String, List<String>> country_hashmap = new HashMap<String, List<String>>();
List<String> my = new ArrayList<String>();
arraylist.add("16873538.webp");
arraylist.add("16873539.webp");
country_hashmap.put("Malaysia", my);

// make another one
List<String> jpn = new ArrayList<String>();
soraru.add("16873540.webp");
soraru.add("16873541.webp");
country_hashmap.put("Japanese", jpn);

for(Map.Entry<String, List<String>> hashmap_data : country_hashmap.entrySet()){
      String key = hashmap_data.getKey(); // contains the keys
      List<String> val = hashmap_data.getValue(); // contains arraylists
      // print all the key and values in the hashmap
      System.out.println(key + ": " +val);

      // using interator to get the specific values arraylists
      Iterator<String> itr = val.iterator();
      int i = 0;
      String[] data = new String[val.size()];
        while (itr.hasNext()){
            String array = itr.next();
            data[i] = array;
            System.out.println(data[i]); // GET THE VALUE
            i++;
        }
  }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.