简体   繁体   English

使用ArrayList作为Java中的值进行映射-为什么为此使用第三方库?

[英]Map with ArrayList as the value in Java - Why use a third party library for this?

I've recently found the need to use a Map with a Long as the key and an ArrayList of objects as the value, like this: 我最近发现有必要使用以Long为键的Map和以对象的ArrayList为值的Map ,如下所示:

Map<Long, ArrayList<Object>>

But I just read here that using a third-party library like Google Guava is recommended for this. 但是我只是在这里读到,建议为此使用第三方库,例如Google Guava。 In particular, a Multimap is recommended instead of the above. 特别是,建议使用Multimap代替上面的方法。

What are the main benefits of using a library to do something so simple? 使用库执行如此简单的操作的主要好处是什么?

I like the ArrayList analogy given above. 我喜欢上面给出的ArrayList类比。 Just as ArrayList saves you from array-resizing boilerplate, Multimap saves you from list-creation boilerplate. 就像ArrayList可以将您从数组大小调整的样板中拯救出来一样, Multimap可以将您从列表创建样板中拯救出来。

Before: 之前:

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

After: 后:

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

And that leads into the next advantage: Since Guava has committed to using Multimap , it includes utilities built around the class. 这带来了下一个优势:由于Guava致力于使用Multimap ,因此它包含围绕该类构建的实用程序。 Using them, the "after" in "before and after" should really be: 使用它们,“之前和之后”中的“之后”应该确实是:

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

Multimaps.index is one of many such utilities. Multimaps.index是许多此类实用程序之一。 Plus, the Multimap class itself provides richer methods than Map<K, List<V>> . 另外, Multimap类本身提供了比Map<K, List<V>>更丰富的方法

What is Guava details some reasoning and benefits. 番石榴是什么详述了一些推理和好处。

For me the biggest reason would be reliability and testing. 对我来说,最大的原因是可靠性和测试。 As mentioned it has been battle-tested at Google, is now very widely used elsewhere and has extensive unit testing. 如前所述,它已经在Google进行了实战测试,现在在其他地方得到了广泛的使用,并且具有广泛的单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM