EzDevInfo.com

guava

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: com.google.common.base.Predicates 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

Lists.transform()

but no

Lists.filter()?

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)

Advertisements

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:

"abc8".split("(?=\\d)|\\W")

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:

Splitter.onPattern("(?=\\d)|\\W").split("abc8")

To my surprise the output changed to:

[abc]

Why?


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
    Optional.absent())
  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

Strings.isNullOrEmpty(str)

Do we have anything similar for Lists? Something like

Lists.isNullOrEmpty(list)

which should be equivalent to

list == null || list.isEmpty()

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

Arrays.isNullOrEmpty(arr)

which should be equivalent to

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

Source: (StackOverflow)

Maven for Eclipse 1.5.0 plugin cannot be installed under Kepler

I downloaded Eclipse Kepler and tried to install M2Eclipse from its update site.

After selecting Maven Integration for Eclipse, I clicked Next and got the following error:

Missing requirement: Maven Integration for Eclipse 1.5.0.20140606-0033 (org.eclipse.m2e.core 1.5.0.20140606-0033) requires 'bundle com.google.guava [14.0.1,16.0.0)' but it could not be found

So I searched through the internet to find out how to install the Guava Eclipse plugin. Some say it's from the Eclipse marketplace, but it cannot be downloaded. I downloaded the binary and tried to copy it to Eclipse's plugin directory. Still the same result.

cp ~/Downloads/guava-16.0.1.jar /Applications/eclipse/plugins/com.google.guava_16.0.1.v1234.jar

How do I install the m2e plugin for Kepler?


Source: (StackOverflow)

Using Google Guava's Objects.ToStringHelper

I used ToStringBuilder.reflectionToString(class) in commons-lang, to implement toString() for simple DTOs. Now I'm trying to use Google Guava instead of Apache commons library. And I found Objects.ToStringHelper in Guava. But it's too verbose if there're lots of members in the class. For example:

@Override
public String toString() {
    return Objects.toStringHelper(this.getClass()).add("name", name)
            .add("emailAddress", emailAddress)
            .add("department", department).add("yearJoined", yearJoined)
            .toString();
}

is much simpler if I use commons-lang:

@Override
public String toString() {
    return ToStringBuilder.reflectionToString(this);
}

Is there any better ways to implement toString() with Guava, not with commons-lang?


Source: (StackOverflow)

Guava: Set + Function = Map?

Is there an idiomatic way to take a Set<K> and a Function<K,V>, and get a Map<K,V> live view? (i.e. the Map is backed by the Set and Function combo, and if e.g. an element is added to the Set, then the corresponding entry also exists in the Map).

(see e.g. Collections2.filter for more discussion on live views)


What if a live view is not needed? Is there something better than this:

public static <K,V> Map<K,V> newMapFrom(Set<K> keys, Function<? super K,V> f) {
    Map<K,V> map = Maps.newHashMap();
    for (K k : keys) {
        map.put(k, f.apply(k));
    }
    return map;
}

Source: (StackOverflow)

Flattening an Iterable> in Guava

Is there a flatten method in Guava - or an easy way to convert an Iterable<Iterable<T>> to an Iterable<T>?

I have a Multimap<K, V> [sourceMultimap] and I want to return all values where the key matches some predicate [keyPredicate]. So at the moment I have:

Iterable<Collection<V>> vals = Maps.filterKeys(sourceMultimap.asMap(), keyPredicate).values();

Collection<V> retColl = ...;
for (Collection<V> vs : vals) retColl.addAll(vs);
return retColl;

I've looked through the Guava docs, but nothing jumped out. I am just checking I've not missed anything. Otherwise, I'll extract my three lines into a short flatten generic method and leave it as that.


Source: (StackOverflow)

is guava-libraries available in maven repo?

I am looking to find guava-libraries in maven repository. It looks like guava is adding more features to google-collections library.


Source: (StackOverflow)

What are the big improvements between guava and apache equivalent libraries?

We currently use apache collections, string utils, etc. I need to decide if we should switch from the apache foundations implementation.

The important criteria is ease of developers use. Performance/memory usage is not yet an important issue for us. Speed of development is the key criteria at this point.

I would appreciate opinions about how the developer's life became significantly easier with guava.


Source: (StackOverflow)

Getting default value for java primitive types

I have a java primitive type at hand:

Class c = int.class; // or long.class, or boolean.class

I'd like to get a 'default value' for this class - specifically the value is assigned to fields of this type if they are not initialized. E.g., '0' for a number, 'false' for a boolean.

Is there a generic way to do this? I tried

c.newInstance()

But I'm getting an InstantiationException, and not a default instance.


Source: (StackOverflow)