Guava 库:它最有用和/或隐藏的功能是什么?

发布于 2024-09-24 06:52:06 字数 333 浏览 2 评论 0 原文

我快速浏览了 Guava API 和新集合它提供的类型(例如,MultimapBiMap 看起来很有用),我正在考虑将该库包含在我从事的项目中。

然而,如果库没有太大好处,并且学习这些功能会浪费宝贵的时间,我也不会随意添加库。

您是否已将 Guava 库包含在您的项目中?它是否以任何意想不到的方式发挥了作用?以后你会一直用它吗?它的主要好处/节省时间是什么?它有哪些隐藏的功能呢?

I have had a quick scan of the Guava API and the new collection types it provides(Multimap and BiMap for example appear useful) and I am thinking of including the library in the project(s) I work on.

However, I also have a reticence to include libraries willy-nilly if they are of no great benefit and learning the features wastes valuable time.

Have you included the Guava library in your project and has it proved useful in any unexpected way? Would you always use it in the future? What has been its main benefit/time saver? What are its hidden features?

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

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

发布评论

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

评论(8

止于盛夏 2024-10-01 06:52:06

说真的,Guava 中的一切都很有用。我已经使用它有一段时间了,并且仍然总是发现我可以用它做一些新的事情,这些事情比手工做需要更少的代码。

其他人没有真正提到我喜欢的一些事情:

  • Multimap 非常棒。任何时候您要使用诸如 Map> 之类的东西时,请使用多重映射,这样可以节省大量繁琐的检查映射到键的现有集合以及创建和添加它的工作如果它不存在。
  • Ordering 非常适合构建按照您想要的方式运行的 Comparator
  • Maps.uniqueIndexMultimaps.index:这些方法采用一个 Iterable 和一个 Function 并构建一个 ImmutableMapImmutableListMultimap,通过将函数应用于每个值的结果来索引 Iterable 中的值。因此,通过检索项目 ID 的函数,您可以在一行中按项目 ID 为项目列表建立索引。
  • 它提供的功能性东西...filtertransform等。尽管使用Functions和Predicate<的类很冗长/code>s,我发现这很有用。 此处
  • ComparisonChain 是一个小型且容易被忽视的类,当您想要编写连续比较多个值的比较方法并在找到第一个差异时应返回时,该类非常有用。它消除了所有繁琐的工作,使其只需几行链式方法调用即可。
  • Objects.equal(Object,Object) - null 安全等于。
  • Objects.hashCode(Object...) - 根据类的多个字段获取哈希码的简单方法。
  • Objects.firstNonNull(Object,Object) - 如果第一个值为 null,则减少获取默认值的代码,特别是如果第一个值是方法调用的结果(您必须分配在以正常方式执行此操作之前将其添加到变量)。
  • CharMatcher 已经提到过,但它们非常强大。
  • Throwables 允许您使用 throwable 做一些不错的事情,例如 Throwables.propagate ,如果它是 RuntimeExceptionError,它会重新抛出 throwable 并将其包装在 RuntimeException 中,否则抛出该异常。

我当然可以继续,但我必须开始工作。 =) 无论如何,尽管我在这里列出了一些我喜欢的东西,但事实是 Guava 中的所有内容在某些情况下都是有用的。其中大部分内容经常有用。当您使用它时,您会发现更多用途。不使用它会感觉有点像一只手被绑在背后。

Seriously, everything in Guava is useful. I've been using it for quite a while, and am still always discovering something new I can do with it that takes less code than doing it by hand.

Some things others have not really mentioned that I love:

  • Multimaps are just great. Any time you would use something like Map<Foo, Collection<Bar>>, use a multimap instead and save yourself a ton of tedious checking for an existing collection mapped to a key and creating and adding it if it isn't there.
  • Ordering is great for building Comparators that behave just how you want.
  • Maps.uniqueIndex and Multimaps.index: these methods take an Iterable and a Function and build an ImmutableMap or ImmutableListMultimap that indexes the values in the Iterable by the result of applying the function to each. So with a function that retrieves the ID of an item, you can index a list of items by their ID in one line.
  • The functional stuff it provides... filter, transform, etc. Despite the verbosity of using classes for Functions and Predicates, I've found this useful. I give an example of one way to make this read nicely here.
  • ComparisonChain is a small, easily overlooked class that's useful when you want to write a comparison method that compares multiple values in succession and should return when the first difference is found. It removes all the tedium of that, making it just a few lines of chained method calls.
  • Objects.equal(Object,Object) - null safe equals.
  • Objects.hashCode(Object...) - easy way to get a hash code based on multiple fields of your class.
  • Objects.firstNonNull(Object,Object) - reduces the code for getting a default value if the first value is null, especially if the first value is the result of a method call (you'd have to assign it to a variable before doing this the normal way).
  • CharMatchers were already mentioned, but they're very powerful.
  • Throwables lets you do some nice things with throwables, such as Throwables.propagate which rethrows a throwable if it's a RuntimeException or an Error and wraps it in a RuntimeException and throws that otherwise.

I could certainly go on, but I have to get to work. =) Anyway, despite my having listed some things I like here, the fact is that everything in Guava is useful in some situation or another. Much of it is useful very often. As you use it, you'll discover more uses. Not using it will feel a bit like having one hand tied behind your back.

贪恋 2024-10-01 06:52:06

我在 Google 内部已经有效地使用 Guava 几年了 - 非常棒。

特别喜欢的部分是:

  • Charsets.* - 如此简单、如此有用的
  • 集合
  • IO 处理(在一行中完全读取资源等)
  • 分割器/连接器
  • 先决条件

I've been effectively using Guava for a couple of years, inside Google - and it's wonderful.

The parts I'm particularly fond of are:

  • Charsets.* - so simple, so useful
  • Collections
  • IO handling (read a resource completely in a single line, etc)
  • Splitter/Joiner
  • Preconditions
回梦 2024-10-01 06:52:06

我最初将它用于集合速记。例如,

Map<String, Map<Long, List<String>>> map = new HashMap<String, Map<Long, List<String>>>();

您可以这样做:

Map<String, Map<Long, List<String>>> map = Maps.newHashMap();

填充地图也很容易:

ImmutableMap<String,String> map = ImmutableMap.of("key1", "value1", "key2", "value2");

现在,我发现了 Guava 中存在的一些其他有用的实用程序。例如,CharMatcher 类允许您匹配字符序列。你可以这样做:

CharMatcher.inRange('a','z').or(inRange('A','Z'));

或者

String phoneNumber = CharMatcher.DIGIT.retainFrom("my phone number is 123456789");

I initially used it for collections shorthands. For example, instead of:

Map<String, Map<Long, List<String>>> map = new HashMap<String, Map<Long, List<String>>>();

you can do this:

Map<String, Map<Long, List<String>>> map = Maps.newHashMap();

It's also easy to populate maps:

ImmutableMap<String,String> map = ImmutableMap.of("key1", "value1", "key2", "value2");

Now, I have discovered some other useful utilities present in Guava. For example, the CharMatcher class allows you to match sequences of characters. You can do:

CharMatcher.inRange('a','z').or(inRange('A','Z'));

or

String phoneNumber = CharMatcher.DIGIT.retainFrom("my phone number is 123456789");
平安喜乐 2024-10-01 06:52:06

CharMatcher 的预计算() 方法 (来源) 是我前几天偶然发现的一个很好的“隐藏功能”。

这实际上只是一种优化,创建一个查找表(使用位数组),然后简单地查找字符以查看它们是否“匹配”。

这是一种您在使用库时可以利用的隐藏优化,您可能在自己的代码中没有想到过这种优化。

当然,
如果您创建一个复杂的 CharMatcher,并且打算多次使用它,则必须记住调用 precompulated() 方法,例如:

CharMatcher complexMatcher = CharMatcher.anyOf("cat")
                                        .or(CharMatcher.DIGIT)
                                        .or(CharMatcher.WHITESPACE)
                                        .precomputed();

CharMatcher's precomputed() method (source) is a nice "hidden feature" I stumbled upon the other day.

It's really just an optimization, that creates a lookup table (using a bit array), and then simply looks up characters to see if they "match".

It's the kind of hidden optimization you can leverage when you use a library, that you might not have thought of yourself in your own code.

Of course,
if you create a complex CharMatcher, which you plan to use many times, you must remember to call the precomputed() method, like:

CharMatcher complexMatcher = CharMatcher.anyOf("cat")
                                        .or(CharMatcher.DIGIT)
                                        .or(CharMatcher.WHITESPACE)
                                        .precomputed();
清晨说晚安 2024-10-01 06:52:06

这是来自 Google 的 YouTube 视频(演讲者:Kevin Bourrillion,Google 核心 Java 库首席工程师)这展示了 Google Collections 的美丽。 Google 所做的一件事(我认为这很出色)就是保证集合的不变性。

Here's a YouTube video from Google (speaker: Kevin Bourrillion, lead engineer for Google's core Java libraries) which shows the beauty of Google Collections. One thing Google did, which I believe is brilliant, is guarantee Immutability in collections.

半山落雨半山空 2024-10-01 06:52:06

Google Guava 是一个实用程序库,因此我怀疑其中是否存在杀手级。关于实用程序的全部内容是您几乎在您拥有的每个项目中都使用它。我不记得我做过的任何项目不使用 Java 集合。事实上,Google Guava 的收集实用程序非常棒,并且应该包含在 Java SDK 本身中。

我写了三篇关于 Google Guava 上的类的文章:

这还不是全部,您还可以做很多其他事情番石榴。

Google Guava is a utility library, so I doubt that there is a killer class inside it. The whole things about utility is you almost use that in every projects you have. I can't remember any project I've done that doesn't use Java collection. And truth is, the collection utility of Google Guava is wonderful and should be in the Java SDK itself.

I've written three articles about classes on Google Guava:

And this is not all, there are many other things you can do with Guava.

葵雨 2024-10-01 06:52:06

绝对非常非常超级有用。它几乎总是第一个添加到新项目的库。

  1. 我们非常喜欢迭代器/迭代器和函数接口。
  2. Service 系列接口是很好的抽象。
  3. 我们非常致力于使用我们的 API 类型的 ImmutableXXX 类来进行通信,因此它无法更改。
  4. 计算地图(来自 MapMaker)在某些情况下非常有用。

总体而言,图书馆的质量非常高。 API 经过深思熟虑,实现也很扎实。强烈推荐。

Absolutely very super useful. It's almost invariably the first library added to a new project.

  1. We're very fond of Iterators/Iterables and the Function interface.
  2. The Service family of interfaces are great abstractions
  3. We're so committed we've started to use the ImmutableXXX classes our API types to communicate that it can't be changed.
  4. Computing maps (from MapMaker) are wonderful in certain situations.

Overall, the library is very high quality. The API is well thought out, the implementation solid. Highly recommended.

唐婉 2024-10-01 06:52:06

MapMaker 现在提供有界 LRU 缓存 - 这是隐藏在微小 API 后面的一些重要机制。这具有巨大的实用潜力,而且我仍然对代码充满兴趣。

MapMaker now offers bounded LRU caches - that's some substantial machinery hidden behind a tiny API. This has the potential for huge utility, and I'm still all over the code.

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