Java 中的多值映射

2022-09-02 13:28:45

我正在研究具有多个参数(1键,2个值)的Hashmap,并且能够为我的问题找到apache多值地图。

这是我的多值地图代码。

import java.util.Set;
import org.apache.commons.collections.map.MultiValueMap;
import org.apache.commons.collections.MultiMap;

public class multiValueMap {

public static void main(String args[]) {
   String a, b, c;
   MultiMap mMap = new MultiValueMap();

   mMap.put("a", "Hello there, It's a wonderful day");
   mMap.put("a", "nice to meet you");

   Set<String> keys = mMap.keySet();

   for (String key : keys) {
      System.out.println("Key = " + key);
      System.out.println("Values = " + mMap.get(key));
      a = String.valueOf(mMap.get(key));

      System.out.println("A : " + a);
    }
 }
}
// The result as below
 Key = a 
 Value = [Hello there, It's a wonderful day, nice to meet you]
 A : [Hello there, It's a wonderful day, nice to meet you]

这是我的问题,我如何存储字符串b的第一个值,第二个存储c的值?如果我子字符串的MultiMap值依赖于“,”,那么它只会在那里存储Hello。请给我有用的建议。


答案 1

您可以尝试以下操作:

String a, b, c;

MultiMap mMap = new MultiValueMap();
mMap.put("a", "Hello there, It's a wonderful day");
mMap.put("a", "nice to meet you");

Set<String> keys = mMap.keySet();

for (String key : keys) {
    System.out.println("Key = " + key);
    System.out.println("Values = " + mMap.get(key));
    List<String> list = (List<String>) mMap.get(key);

    b = list.get(0);
    c = list.get(1);
    System.out.println("B : " + b);
    System.out.println("C : " + c);
} 

答案 2

您不必进行拆分。这是找到的 MultiMap 的文档:

MultiMap mhm = new MultiHashMap();
 mhm.put(key, "A");
 mhm.put(key, "B");
 mhm.put(key, "C");
 Collection coll = (Collection) mhm.get(key);

现在,当您在多地图上进行调用时,它会为您提供一个集合。第一项将是你的 b,第二项将是你的 c。get()