You are currently viewing Getting Started with Guava

Getting Started with Guava

  • Post author:
  • Post category:Guava
  • Post comments:0 Comments
  • Post last modified:March 31, 2024

Guava is an open-source Java library developed by Google. It provides a wide range of utilities and helper functions to make Java programming easier and more efficient. In this tutorial, we’ll explore some of the key features of Guava and how you can integrate it into your Java projects.

Table of Contents

  1. Introduction to Guava
  2. Installation
  3. Common Utilities
  1. Optional
  2. EventBus
  3. Conclusion

1. Introduction to Guava

Guava provides a wide range of utilities for common programming tasks such as working with collections, strings, primitives, and functional programming. It also includes additional features like caching, concurrency, and event publishing.

Key features of Guava:

  • Preconditions: Simplifies checking method preconditions.
  • Objects: Simplifies common object-related tasks.
  • Strings: Provides additional string manipulation methods.
  • Collections: Enhanced collections and collection-related utilities.
  • Optional: A type that represents an optional value.
  • EventBus: Publish-subscribe event bus for handling application events.

2. Installation

To use Guava in your Java project, you need to include the Guava dependency in your pom.xml (for Maven) or build.gradle (for Gradle).

Maven

Add the following dependency to your pom.xml:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

Gradle

Add the following dependency to your build.gradle:

implementation 'com.google.guava:guava:31.0.1-jre'

3. Common Utilities

Preconditions

Guava’s Preconditions class provides static methods to check method arguments for validity.

import com.google.common.base.Preconditions;

public class Example {
    public static void main(String[] args) {
        int value = -1;
        Preconditions.checkArgument(value >= 0, "Value must be non-negative");
    }
}

Objects

The Objects class simplifies common object-related tasks such as comparing objects for equality, creating hash codes, and checking for null.

import com.google.common.base.Objects;

public class Example {
    public static void main(String[] args) {
        String a = "Hello";
        String b = "Hello";
        System.out.println(Objects.equal(a, b)); // true
    }
}

Strings

Guava’s Strings class provides additional string manipulation methods.

import com.google.common.base.Strings;

public class Example {
    public static void main(String[] args) {
        String str = "   Hello, Guava   ";
        System.out.println(Strings.isNullOrEmpty(str)); // false
        System.out.println(Strings.nullToEmpty(str)); // "   Hello, Guava   "
        System.out.println(Strings.emptyToNull("")); // null
        System.out.println(Strings.repeat("Guava ", 3)); // "Guava Guava Guava "
        System.out.println(Strings.padStart("123", 5, '0')); // "00123"
    }
}

Collections

Guava provides enhanced collections and collection-related utilities.

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;

import java.util.List;

public class Example {
    public static void main(String[] args) {
        List<Integer> numbers = Lists.newArrayList(1, 2, 3, 4, 5);
        List<Integer> immutableList = ImmutableList.of(1, 2, 3);

        System.out.println(numbers); // [1, 2, 3, 4, 5]
        System.out.println(immutableList); // [1, 2, 3]
    }
}

Functional Programming

Guava supports functional programming style with its Function, Predicate, and Supplier interfaces.

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;

import java.util.Collection;
import java.util.List;

public class Example {
    public static void main(String[] args) {
        List<String> names = Lists.newArrayList("Alice", "Bob", "Charlie");

        // Transform each name to uppercase
        Collection<String> uppercaseNames = Collections2.transform(names, new Function<String, String>() {
            public String apply(String input) {
                return input.toUpperCase();
            }
        });

        // Filter names starting with 'A'
        Collection<String> filteredNames = Collections2.filter(names, new Predicate<String>() {
            public boolean apply(String input) {
                return input.startsWith("A");
            }
        });

        System.out.println(uppercaseNames); // [ALICE, BOB, CHARLIE]
        System.out.println(filteredNames); // [Alice]
    }
}

4. Optional

Guava’s Optional is a type that represents an optional value. It can contain either a non-null value or be empty. It helps to avoid null checks and NullPointerExceptions.

import com.google.common.base.Optional;

public class Example {
    public static void main(String[] args) {
        Optional<String> optional = Optional.of("Hello");
        System.out.println(optional.isPresent()); // true
        System.out.println(optional.get()); // "Hello"

        Optional<String> absentOptional = Optional.absent();


        System.out.println(absentOptional.isPresent()); // false
        // System.out.println(absentOptional.get()); // Throws IllegalStateException
    }
}

5. EventBus

Guava’s EventBus is a publish-subscribe event bus for handling application events. It allows components to communicate without being directly dependent on each other.

Creating an EventBus

import com.google.common.eventbus.EventBus;

public class Example {
    public static void main(String[] args) {
        EventBus eventBus = new EventBus("example");

        // Register subscribers
        eventBus.register(new EventSubscriber());

        // Publish events
        eventBus.post(new Event("Hello, Guava EventBus!"));
    }
}

class EventSubscriber {
    @Subscribe
    public void handleEvent(Event event) {
        System.out.println("Received event: " + event.getMessage());
    }
}

class Event {
    private String message;

    public Event(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

6. Conclusion

Guava is a powerful library that provides a wide range of utilities and helper functions to make Java programming more efficient. In this tutorial, we’ve covered some of the common utilities like Preconditions, Objects, Strings, Collections, Functional Programming, Optional, and EventBus. Integrating Guava into your Java projects can help simplify your code and improve readability.

Additional Resources:

Leave a Reply