Introducing Google Guava. Guava is an open-source “Collection... | by Mohit Sharma | Towards Data Science

It provides utilities for working with Java collections. As you dive deep into Guava you’ll notice how it reduces coding errors, facilitates standard coding practices and boost productivity by making code concise and easy to read.
I’ve decided to break down the Guava tutorial in a series of posts. We’ll cover a lot of Guava concepts — Guava utility classes, functional programming, working with collections, and Event bus.
In this post, you’ll learn about:1. Adding Guava to your Java project.2. Basic utilities in Guava — Splitter, MapSplitter, Joiner, MapJoiner, and Precondition class
Guava comes in two flavors
One for use on a Java 8+ JavaRuntimeEnvironment.Another for use on a Java 7 or Android Platform.
One for use on a Java 8+ JavaRuntimeEnvironment.
Another for use on a Java 7 or Android Platform.
If you’re using Maven, add the following snippet to <dependencies>...</dependencies> section
<dependency>    <groupId>com.google.guava</groupId>    <artifactId>guava</artifactId>    <version>version</version></dependency>
If you’re using Gradle, add mavenCentral() to repositories
repositories {    mavenCentral()}
And then add the following snippet to dependencies section of build.gradle file.
dependencies {    compile group:'com.google.guava’, name:'guava', version:version}
Check out link for more information on version.
For people who are not using any project management tool like Maven or Gradle —
Download JAR of Google Guava from here.If you’re using IDE, add JAR file as an external library.If you’re using text editor, add JAR file to your class-path.
Download JAR of Google Guava from here.
If you’re using IDE, add JAR file as an external library.
If you’re using text editor, add JAR file to your class-path.
2.1 Joiner ClassIt takes arbitrary strings and concatenate them together with some delimiter token. The result is built by calling Object.toString() for each element.
Typically you’d do something like
public String concatenateStringsWithDelimiter(List<String> strList, String delimiter) {    StringBuilder builder = new StringBuilder();    for (String str: strList)         if (str != null)             builder.append(str).append(delimiter);    // To remove the delimiter from the end    builder.setLength(builder.length() - delimiter.length());    return builder.toString();}
But with the help of Joiner Class, code equivalent to above can be written as
Joiner.on(delimiter).skipNulls().join(strList);
So as you can see, the code becomes concise and maintainable. Also finding bugs is relatively easy with Guava.Now what if you want to add a replacement for null strings? Well, Joiner class takes care of this situation too.
Joiner.on(delimiter).useForNull(replacement).join(strList);
You might be thinking that maybe Joiner class is limited to working with Strings only but this is not the case. Since it is implemented as Generic class, you could pass an array, iterable or varargs of any object too.Joiner class is immutable once it is created. So, it is thread-safe and can be used as static final variable.
public static final Joiner jnr = Joiner.on(delimiter).skipNulls();String result = jnr.append(strList);
2.2 Joiner.MapJoiner ClassIt works same as the Joiner Class with the only difference that it joins the given string as key-value pair with specified key-value separator.
public void DemoMapJoiner() {    // Initialising Guava LinkedHashMap Collection    Map<String, String> myMap = Maps.newLinkedHashMap();    myMap.put(“India”, “Hockey”);    myMap.put(“England”, “Cricket”);    String delimiter = “#”;    String separator = “=”;    String result = Joiner.on(delimiter).withKeyValueSeperator(separator).join(myMap);    String expected = “India=Hocket#England=Cricket”;    assertThat(result, expected);}
2.3 Splitter ClassSplitter class does opposite of what Joiner class does. It takes a string with some delimiter (a character, a string or even a regex pattern) and split that string on delimiter and obtain an array of the parts.
Typically you’d do something like
String test = “alpha,beta,gamma,,delta,,”;String[] parts = test.split(“,”);// parts = {“alpha”, “beta”, “gamma”, “”, “delta”, “”};
Can you notice the issue? You don’t want empty strings to be part of my result. So, split() method is leaving something to be desired.
But with the help of Splitter Class, code equivalent to above can be written as
Splitter splitter = Splitter.on(“,”);String[] parts = splitter.split(test);
split() method returns an iterable object containing individual string parts from test string. trimResults() method can be used to remove leading and trailing whitespaces from results.
Just like Joiner class, Splitter class also is immutable once it is created. So, it is thread-safe and can be used as static final variable.
2.4 MapSplitter ClassSplitter class is accompanied by MapSplitter. It takes in a string in which key-value pairs are delimited by some delimiter (a character, a string or even a regex pattern) and returns Map instance with key-value pair in same order as in original string.
public void DemoMapSplitter() {    String test = “India=Hocket#England=Cricket”;     // Initialising Guava LinkedHashMap Collection    Map<String, String> myTestMap = Maps.newLinkedHashMap();    myMap.put(“India”, “Hockey”);    myMap.put(“England”, “Cricket”);    String delimiter = “#”;    String seperator = “=”;    Splitter.MapSplitter mapSplitter = Splitter.on(delimiter).withKeyValueSeperator(seperator);    Map<String, String> myExpectedMap = mapSplitter.split(test);    assertThat(myTestMap, myExpectedMap);}
2.5 Precondition ClassPrecondition class provides collection of static methods to check the state of our code. Preconditions are important because they guarantee out expectations for successful code are met.
For example:1. Checking for null conditions. You can always write
if (testObj == null)        throw new IllegalArgumentException(“testObj is null”);
Using Precondition class makes it more concise and easy-to-use
checkNotNull(testObj, “testObj is null”);
2. Checking for valid arguments.
public void demoPrecondition {    private int age;    public demoPrecondition(int age) {    checkArgument(age > 0, “Invalid Age”);        this.age = age;    }}
checkArgument(exp, msg) evaluates state of variable passed as parameter to a method. It evaluates a boolean expression exp and throws IllegalArgumentException if expression evaluates to false.
3. Checking state of an object
public void demoPrecondition {        private String name;        public demoPrecondition(String name) {            this.name = checkNotNull(name, “Anonamous”);        }        public void Capitalize() {            checkState(validate(), “Empty Name”);            }                private bool validate() { this.name.length() > 0; }    }
checkState(exp, msg) evaluates state of object not argument passed to a method. It evaluates a boolean expression exp and throws IllegalArgumentException if expression evaluates to false.
4. Checking valid element index
public void demoPrecondition {        int size;        private int [] price;                public demoPrecondition(int size) {            this.size = checkArgument(size > 0, “size must be greater than 0”);           this.price = new int[this.size];        }        public void updateItem(int index, int value) {            int indexToBeUpdated = checkElementIndex(index, this.size, “Illegal Index Access”);        }    }
Thanks for the read. In the next post, we’ll talk about Functional Programming in Guava.