Google Core Libraries for Java 6+

Managing highly repetitive code and documentation in Java

Highly repetitive code is generally a bad thing, and there are design patterns that can help minimize this. However, sometimes it's simply inevitable due to the constraints of the language itself. Take the following example from java.util.Arrays:

 * Assigns the specified long value to each element of the specified
 * range of the specified array of longs.  The range to be filled
 * extends from index <tt>fromIndex</tt>, inclusive, to index
 * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
 * range to be filled is empty.)
 * @param a the array to be filled
 * @param fromIndex the index of the first element (inclusive) to be
 *        filled with the specified value
 * @param toIndex the index of the last element (exclusive) to be
 *        filled with the specified value
 * @param val the value to be stored in all elements of the array
 * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
 * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
 *         <tt>toIndex &gt; a.length</tt>
public static void fill(long[] a, int fromIndex, int toIndex, long val) {
    rangeCheck(a.length, fromIndex, toIndex);
    for (int i=fromIndex; i<toIndex; i++)
        a[i] = val;

The above snippet appears in the source code 8 times, with very little variation in the documentation/method signature but exactly the same method body, one for each of the root array types int[], short[], char[], byte[], boolean[], double[], float[], and Object[].

I believe that unless one resorts to reflection (which is an entirely different subject in itself), this repetition is inevitable. I understand that as a utility class, such high concentration of repetitive Java code is highly atypical, but even with the best practice, repetition does happen! Refactoring doesn't always work because it's not always possible (the obvious case is when the repetition is in the documentation).

Obviously maintaining this source code is a nightmare. A slight typo in the documentation, or a minor bug in the implementation, is multiplied by however many repetitions was made. In fact, the best example happens to involve this exact class:

Google Research Blog - Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken (by Joshua Bloch, Software Engineer)

The bug is a surprisingly subtle one, occurring in what many thought to be just a simple and straightforward algorithm.

    // int mid =(low + high) / 2; // the bug
    int mid = (low + high) >>> 1; // the fix

The above line appears 11 times in the source code!

So my questions are:

  • How are these kinds of repetitive Java code/documentation handled in practice? How are they developed, maintained, and tested?
    • Do you start with "the original", and make it as mature as possible, and then copy and paste as necessary and hope you didn't make a mistake?
    • And if you did make a mistake in the original, then just fix it everywhere, unless you're comfortable with deleting the copies and repeating the whole replication process?
    • And you apply this same process for the testing code as well?
  • Would Java benefit from some sort of limited-use source code preprocessing for this kind of thing?
    • Perhaps Sun has their own preprocessor to help write, maintain, document and test these kind of repetitive library code?

A comment requested another example, so I pulled this one from Google Collections: lines 276-310 (AndPredicate) vs lines 312-346 (OrPredicate).

The source for these two classes are identical, except for:

  • AndPredicate vs OrPredicate (each appears 5 times in its class)
  • "And(" vs Or(" (in the respective toString() methods)
  • #and vs #or (in the @see Javadoc comments)
  • true vs false (in apply; ! can be rewritten out of the expression)
  • -1 /* all bits on */ vs 0 /* all bits off */ in hashCode()
  • &= vs |= in hashCode()

Source: (StackOverflow)

Guava: Why is there no Lists.filter() function?

is there a reason there's


but no


How do i filter a list correctly? I could use

new List(Collection2.filter())

of course, but this way it's not guaranteed that my ordering stays the same, if i understand correctly.

Source: (StackOverflow)

What's the point of Guava's Optional class

I've recently read about this and seen people using this class, but in pretty much all cases, using null would've worked as well - if not more intuitively. Can someone provide a concrete example where Optional would achieve something that null couldn't or in a much cleaner way? The only thing I can think of is to use it with Maps that don't accept null keys, but even that could be done with a side "mapping" of null's value. Can anyone provide me with a more convincing argument? Thank you.

Source: (StackOverflow)

Predicate in Java

I am going through the code which uses Predicate in Java. I have never used predicate. Can someone guide me to any tutorial or conceptual explanation of predicate and their implementation in java ? Google didnt help much...

Source: (StackOverflow)

How is Guava Splitter.onPattern(..).split() different from String.split(..)?

I recently harnessed the power of a look-ahead regular expression to split a String:


If printed to the console this expression returns:

[abc, 8]

Very pleased with this result, I wanted to transfer this to Guava for further development, which looked like this:


To my surprise the output changed to:



Source: (StackOverflow)

The Guava library for java; what are its most useful and/or hidden features [closed]

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 ?

Source: (StackOverflow)

Should I use Java8/Guava Optional for every method that may return null?

Optional is used to represent nullable object, Some uses of this class include

  1. As a method return type, as an alternative to returning null to
    indicate that no value was available
  2. To distinguish between "unknown" (for example, not present in a map) and "known to have no value" (present in the map, with value
  3. To wrap nullable references for storage in a collection that does not support null (though there are several other approaches to this that should be considered first)

For the first case, do I need to return Optional in all nullable return method?

Source: (StackOverflow)

Google Guava isNullOrEmpty for collections

I see that Guava has isNullOrEmpty utility method for Strings


Do we have anything similar for Lists? Something like


which should be equivalent to

list == null || list.isEmpty()

Also, do we have anything similar for Arrays? Something like


which should be equivalent to

arr == null || arr.length == 0

Source: (StackOverflow)

Google-guava checkNotNull and IntelliJ IDEA's "may produce java.lang.NullPointerException"

Is there any way to suppress this warning:

    MyClass object = null;

    /*Some code that 'might' set this object but I know it will*/      

    //when "assert object != null" is used here no warning is shown

    //"May produce 'java.lang.NullPointerException'" warning here 

I'm using IntelliJ IDEA 10.5 and I know this warning is unnecessary however I would like to suppress it just here and avoid switching inspections off.

Source: (StackOverflow)

Guava libraries and GWT

Just discovered the Guava libraries project.

Do these work with GWT?

Source: (StackOverflow)

Is there an elegant way to remove nulls while transforming a Collection using Guava?

I have a question about simplifying some Collection handling code, when using Google Collections (update: Guava).

I've got a bunch of "Computer" objects, and I want to end up with a Collection of their "resource id"s. This is done like so:

Collection<Computer> matchingComputers = findComputers();
Collection<String> resourceIds = 
    Lists.newArrayList(Iterables.transform(matchingComputers, new Function<Computer, String>() {
    public String apply(Computer from) {
        return from.getResourceId();

Now, getResourceId() may return null (and changing that is not an option right now), yet in this case I'd like to omit nulls from the resulting String collection.

Here's one way to filter nulls out:

Collections2.filter(resourceIds, new Predicate<String>() {
    public boolean apply(String input) {
        return input != null;

You could put all that together like this:

Collection<String> resourceIds = Collections2.filter(
Lists.newArrayList(Iterables.transform(matchingComputers, new Function<Computer, String>() {
    public String apply(Computer from) {
        return from.getResourceId();
})), new Predicate<String>() {
    public boolean apply(String input) {
        return input != null;

But this is hardly elegant, let alone readable, for such a simple task! In fact, plain old Java code (with no fancy Predicate or Function stuff at all) would arguably be much cleaner:

Collection<String> resourceIds = Lists.newArrayList();
for (Computer computer : matchingComputers) {
    String resourceId = computer.getResourceId();
    if (resourceId != null) {

Using the above is certainly also an option, but out of curiosity (and desire to learn more of Google Collections), can you do the exact same thing in some shorter or more elegant way using Google Collections?

Source: (StackOverflow)

Interface/enum listing standard mime-type constants

I am looking among the standard libraries (like apache commons, jax, jboss, javax) for an interface or enum that lists the values of all the standard mime-type (aka content-type).

This interface should not be encumbered with too deep with other classes that would make it difficult to include the whole bunch as gwt source code.

for example

interface ContentType{
  String JSON = "Application/JSON";
  blah ... blah ...


enum ContentType{
  blah ... blah ...

Source: (StackOverflow)

Are there tutorials and resources explaining all components of guava-libraries?

I still precise that this request doesn't concern the google-collections part of the library which has a lot of resources: I'm speaking essentially about the services and the concurrency part.

I couldn't find tutorials regarding guava that aren't fully collections oriented. I know the collections are the most important part of the library, but others look interesting while they don't have much associated documentation.

Source: (StackOverflow)

Map implementation with duplicate keys

I want to have Map with duplicate keys, I know there are many Map implementations(eclipse shows me about 50), so I bet there must be one that allows this. I know its easy to write your own Map that does this, but i would rather use some existing solution. Maybe something in commons-collections or google-collections?

Source: (StackOverflow)

Combine multiple Collections into a single logical Collection?

Assume, I have a constant number of collections (e.g. 3 ArrayLists) as members of a class. Now, I want to expose all the elements to other classes so they can simply iterate over all elements (ideally, read only). I'm using guava collections and I wonder how I could use guava iterables/iterators to generate a logical view on the internal collections without making temporary copies.

Source: (StackOverflow)