Guava MultiSet 与 Map?

发布于 12-27 03:14 字数 67 浏览 2 评论 0原文

我对Multiset的理解是一个带有频率的集合,但是我总是可以使用Map来表示频率,还有其他原因使用Multiset吗?

My understanding of Multiset is a set with frequency, but I can always use Map to represent the frequency, is there other reason to use Multiset?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

筱果果 2025-01-03 03:14:16

Multiset 相对于 Map 的优点:

  • 添加集合中尚不存在的元素时不需要特殊代码。
  • 直接处理元素计数的方法:count(E)add(E, int)等,
  • 代码的意图更加清晰。 Multiset 显然将元素映射到它们的计数。 Map 可以将元素映射到任意整数。

另请参阅:

Multiset Javadoc

< a href="https://github.com/google/guava/wiki/NewCollectionTypesExplained#multiset" rel="nofollow noreferrer">Guava Wiki 中解释的 Multiset

Advantages of a Multiset<E> over a Map<E, Integer>:

  • No special code required when adding an element that is not already in the collection.
  • Methods for handling the count of elements directly: count(E), add(E, int), etc.
  • The intention of the code is clearer. A Multiset<E> obviously maps the elements to their counts. A Map<E, Integer> could map the elements to arbitrary integers.

See also:

Multiset Javadoc

Multiset explained in the Guava Wiki

黎歌 2025-01-03 03:14:16

对我而言,MultisetMap 的最重要区别在于它是一个 Collection:您只需将内容放入其中即可稍后计数。从概念上讲,它适合其设计的用例,而 Map 则不适合。对于这些用例,Map 只是一种可以正常工作的 hack,因为 Java 没有提供任何更合适的东西。

To me, the most important point that sets Multiset apart from a Map is that it's a Collection: you just put stuff into it and you can get counts later. It conceptually fits the use cases for which it's designed where a Map does not. For those use cases, a Map is just a hack that kinda-sorta works OK since Java didn't provide anything more appropriate.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文