【问题标题】:Dynamically Created ArrayList From User Input Without MultiMap从没有 MultiMap 的用户输入动态创建的 ArrayList
【发布时间】:2015-01-07 06:21:49
【问题描述】:

我正在尝试在不使用 MultiMap 的情况下获取用户输入并将数据排序到 HashMap 内的多个 ArrayList 中。 我目前有这个声明:

HashMap<Integer, ArrayList<String>> myMap = new HashMap<Integer, ArrayList<String>>();

用户输入的示例如下所示:

1 String
2 String
2 String_b
3 String

我需要生成的地图是什么样子的:

[1]
  ---- String
[2]
  ---- String
  ---- String_b
[3]
  ---- String

我一直在环顾四周,发现 Guava 创建了一些涉及 MultiMap 的东西。完美的场景是能够执行myMap.put(1, "String"); myMap.put(1, "String_b"); 之类的操作,这样我就可以单独添加每个元素,而不必先创建 ArrayList。

如果我需要澄清,请告诉我!

【问题讨论】:

  • 啊,是的。谢谢。试图看看这是否可以在没有 MultiMap 的情况下完成。我会在正文/标题中更清楚地说明这一点。

标签: java loops arraylist hashmap


【解决方案1】:

这就是 Guava 的 MultiMap 可以做到的:

Multimap<Integer, String> myMultimap = ArrayListMultimap.create();

myMultimap.put(1, "a");
myMultimap.put(1, "b");
myMultimap.put(1, "c");
myMultimap.put(2, "x");

另一个选项是来自 Apache Commons Collections 的 MultiMap

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

【讨论】:

  • 有没有不使用 MutliMap 的方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多