java 中的多值映射

MultiValueMap in java

我正在学习具有多个参数(1 个键,2 个值)的 Hashmap 我能够为我的问题找到 apache multiValueMap。

这是我的 multiValueMap 代码。

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 存储在那里。 请给我有用的建议。

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

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

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

您可以尝试以下操作:

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);
} 

您还可以使用键和对象在 Multimap 中存储多个值。 像这样的东西, MultiValueMap mv = new LinkedMultiValueMap<~>();

@user3810857 你必须用从数据库中检索到的 3 个字段(数据编号(整数)、通道 ID(整数)、描述(字符串))制作一个包装器,然后你可以根据您对 wrapper 的要求作为您的价值。