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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3759440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 04:32:09  来源:igfitidea点击:

The Guava library: What are its most useful and/or hidden features?

javaguava

提问by NimChimpsky

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

我有过的快速扫描番石榴API,它提供了新的集合类型(Multimap以及BiMap例如出现有用),我想包括在项目(S)在我工作的图书馆。

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?

您是否在您的项目中包含了 Guava 库,并证明它以任何意想不到的方式有用?你以后会一直用吗?它的主要好处/节省时间是什么?它的隐藏功能是什么?

采纳答案by ColinD

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.
  • Orderingis great for building Comparators that behave just how you want.
  • Maps.uniqueIndexand Multimaps.index: these methods take an Iterableand a Functionand build an ImmutableMapor ImmutableListMultimapthat indexes the values in the Iterableby 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.
  • ComparisonChainis 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.
  • Throwableslets you do some nice things with throwables, such as Throwables.propagatewhich rethrows a throwable if it's a RuntimeExceptionor an Errorand wraps it in a RuntimeExceptionand throws that otherwise.
  • Multimap真是太棒了。任何时候您会使用类似的东西时Map<Foo, Collection<Bar>>,请改用 multimap 并为自己节省大量繁琐的检查映射到键的现有集合并在它不存在时创建和添加它的工作。
  • Ordering非常适合构建Comparator按照您想要的方式运行的 s。
  • Maps.uniqueIndexand Multimaps.index:这些方法采用 anIterable和 aFunction并构建一个ImmutableMapor ImmutableListMultimapIterable通过将函数应用于每个的结果来索引 中的值。因此,使用检索项目 ID 的函数,您可以在一行中按项目的 ID 索引项目列表。
  • 它提供的功能性的东西... filtertransform等等。尽管为Functions 和Predicates使用类很冗长,但我发现这很有用。我给的一种方式的例子来说明这很好地读这里
  • ComparisonChain是一个很小的、容易被忽视的类,当你想编写一个比较方法来连续比较多个值并且在找到第一个差异时应该返回时很有用。它消除了所有的乏味,使它只是几行链式方法调用。
  • Objects.equal(Object,Object)- null 安全等于。
  • Objects.hashCode(Object...)- 根据类的多个字段获取哈希码的简单方法。
  • Objects.firstNonNull(Object,Object)- 如果第一个值为空,则减少获取默认值的代码,特别是如果第一个值是方法调用的结果(在以正常方式执行此操作之前,您必须将其分配给变量)。
  • CharMatchers 已经提到过,但它们非常强大。
  • Throwables让您可以使用 throwable 做一些不错的事情,例如Throwables.propagate如果它是 aRuntimeException或 an则重新抛出一个 throwableError并将其包装在 a 中RuntimeException,否则抛出它。

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.

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

回答by Jon Skeet

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

几年来,我一直在 Google 内部有效地使用 Guava - 这很棒。

The parts I'm particularlyfond of are:

特别喜欢的部分是:

  • Charsets.*- so simple, so useful
  • Collections
  • IO handling (read a resource completely in a single line, etc)
  • Splitter/Joiner
  • Preconditions
  • Charsets.*- 如此简单,如此有用
  • 收藏
  • IO 处理(在一行中完全读取资源等)
  • Splitter/Joiner
  • Preconditions

回答by nanda

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.

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

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

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

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

这还不是全部,您还可以使用 Guava 做许多其他事情。

回答by Buhake Sindi

Here's a YouTube videofrom 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 guaranteeImmutability in collections.

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

回答by dogbane

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 CharMatcherclass allows you to match sequences of characters. You can do:

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

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

or

或者

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

回答by Etienne Neveu

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

CharMatcher 的 precomputed() 方法(source是我前几天偶然发现的一个很好的“隐藏功能”。

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,你打算多次使用它,你必须记住调用 precomputed() 方法,例如:

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

回答by Darren Gilroy

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.
  1. 我们非常喜欢 Iterators/Iterables 和 Function 接口。
  2. 服务接口系列是很好的抽象
  3. 我们非常投入,我们已经开始使用我们的 API 类型的 ImmutableXXX 类来传达它无法更改。
  4. 计算地图(来自 MapMaker)在某些情况下非常有用。

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

总的来说,图书馆的质量非常高。API经过深思熟虑,实现可靠。强烈推荐。

回答by Dimitris Andreou

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.

MapMaker 现在提供有界 LRU 缓存——这是隐藏在微小 API 后面的一些重要机制。这具有巨大效用的潜力,我仍然在代码中。