【问题标题】:Map with ArrayList as the value in Java - Why use a third party library for this?使用 ArrayList 作为 Java 中的值的映射 - 为什么要为此使用第三方库?
【发布时间】:2014-06-22 19:30:31
【问题描述】:

我最近发现需要使用 MapLong 作为键和对象的 ArrayList 作为值,如下所示:

Map<Long, ArrayList<Object>>

但我刚刚读到 here 建议为此使用像 Google Guava 这样的第三方库。特别是,建议使用Multimap 而不是上面的。

使用库来做如此简单的事情的主要好处是什么?

【问题讨论】:

  • 简答:抽象。这就像在问“既然可以简单地手动管理数组,为什么还要使用ArrayList?”
  • 所以它只是让你的代码更简单?编辑:好的,我明白你在说什么。
  • 据我所知,是的。这本身就足以使用它。如果有任何性能差异,我不知道。
  • Guava 确实有一些很酷的类可以让某些任务变得更容易,但你所做的绝不是罕见或复杂的。
  • @JDJ 请参阅this video,它已有 5 年历史,但涵盖了 Guava(以前的 Google 收藏)基础知识,包括 Multimap 主题(从第二部分开始,here's direct link)。跨度>

标签: arraylist map guava java


【解决方案1】:

我喜欢上面给出的ArrayList 类比。就像 ArrayList 让您免于调整数组大小样板一样,Multimap 让您免于创建列表样板。

之前:

Map<String, List<Connection>> map =
    new HashMap<>();
for (Connection connection : connections) {
  String host = connection.getHost();
  if (!map.containsKey(host)) {
    map.put(host, new ArrayList<Connection>());
  }
  map.get(host).add(connection);
}

之后:

Multimap<String, Connection> multimap =
    ArrayListMultimap.create();
for (Connection connection : connections) {
  multimap.put(connection.getHost(), connection);
}

这带来了下一个优势:由于 Guava 已承诺使用 Multimap,因此它包含围绕该类构建的实用程序。使用它们,“之前和之后”中的“之后”应该是:

Multimap<String, Connection> multimap =
    Multimaps.index(connections, Connection::getHost);

Multimaps.index 是众多此类实用程序之一。另外,the Multimap class itself provides richer methods than Map&lt;K, List&lt;V&gt;&gt;

【讨论】:

    【解决方案2】:

    What is Guava 详细说明了一些推理和好处。

    对我来说,最大的原因是可靠性和测试。如前所述,它已经在 Google 进行了实战测试,现在在其他地方得到了非常广泛的应用,并且进行了广泛的单元测试。

    【讨论】:

      猜你喜欢
      • 2014-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      相关资源
      最近更新 更多