Convert Figma logo to code with AI

google logoguava

Google core libraries for Java

49,988
10,856
49,988
716

Top Related Projects

Apache Commons Lang

Joda-Time is the widely used replacement for the Java date and time classes prior to Java SE 8.

Spring Framework

47,834

RxJava – Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.

14,240

Vert.x is a tool-kit for building reactive applications on the JVM

33,257

Netty project - an event-driven asynchronous network application framework

Quick Overview

Guava is an open-source set of core Java libraries developed by Google. It provides utility classes for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and more. Guava aims to improve and extend the Java standard libraries with efficient, tested, and well-documented code.

Pros

  • Comprehensive set of utilities that enhance Java's standard libraries
  • Well-tested and production-ready, used extensively within Google
  • Excellent documentation and active community support
  • Improves code readability and reduces boilerplate code

Cons

  • Can increase the size of your application due to its large codebase
  • Some features may overlap with newer Java versions, potentially causing confusion
  • Learning curve for developers unfamiliar with Guava's idioms
  • Dependency management can be challenging in large projects

Code Examples

  1. Using Immutable Collections:
import com.google.common.collect.ImmutableList;

ImmutableList<String> immutableList = ImmutableList.of("apple", "banana", "cherry");

This creates an immutable list of strings, which cannot be modified after creation.

  1. Preconditions for input validation:
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

public void processUser(String username, int age) {
    checkNotNull(username, "Username cannot be null");
    checkArgument(age >= 18, "User must be at least 18 years old");
    // Process user...
}

This demonstrates using Guava's Preconditions to validate method arguments.

  1. Using MultiMap:
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("fruit", "apple");
multimap.put("fruit", "banana");
multimap.put("vegetable", "carrot");

System.out.println(multimap.get("fruit")); // Outputs: [apple, banana]

This example shows how to use Guava's Multimap to associate multiple values with a single key.

Getting Started

To start using Guava in your Java project, add the following dependency to your Maven pom.xml file:

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

For Gradle, add this to your build.gradle file:

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

After adding the dependency, you can start using Guava's utilities in your Java code by importing the required classes.

Competitor Comparisons

Apache Commons Lang

Pros of Commons Lang

  • Smaller library size, leading to reduced dependency footprint
  • More focused on string manipulation and utility functions
  • Longer history and wider adoption in legacy Java projects

Cons of Commons Lang

  • Less comprehensive feature set compared to Guava
  • Slower development pace and less frequent updates
  • Limited support for functional programming paradigms

Code Comparison

Commons Lang:

String result = StringUtils.capitalize("hello");
boolean isEmpty = StringUtils.isEmpty(myString);
String[] parts = StringUtils.split(text, ",");

Guava:

String result = Ascii.toUpperCase(string.charAt(0)) + string.substring(1);
boolean isEmpty = Strings.isNullOrEmpty(myString);
List<String> parts = Splitter.on(',').splitToList(text);

Both libraries offer utility methods for common tasks, but Guava often provides more sophisticated options and better support for modern Java features. Commons Lang focuses on simplicity and core Java functionality, while Guava offers a broader range of utilities and data structures.

Commons Lang is a good choice for projects that need basic string and object utilities without introducing a large dependency. Guava is better suited for larger projects that can benefit from its extensive feature set and performance optimizations.

Joda-Time is the widely used replacement for the Java date and time classes prior to Java SE 8.

Pros of Joda-Time

  • Specialized focus on date and time handling
  • More comprehensive date/time operations and manipulations
  • Better support for different calendar systems

Cons of Joda-Time

  • Limited to date and time functionality
  • Less actively maintained compared to Guava

Code Comparison

Joda-Time:

DateTime now = new DateTime();
DateTime tomorrow = now.plusDays(1);
Period period = new Period(now, tomorrow);

Guava:

Instant now = Instant.now();
Instant tomorrow = now.plus(Duration.ofDays(1));
Duration duration = Duration.between(now, tomorrow);

Additional Notes

Joda-Time is a specialized library for date and time operations, while Guava is a more general-purpose utility library. Guava includes a wider range of utilities beyond date/time handling, such as collections, caching, and string processing.

Joda-Time was the de facto standard for date and time handling in Java before the introduction of the java.time package in Java 8. Since then, its usage has declined, and it's now in maintenance mode.

Guava, on the other hand, is actively maintained by Google and continues to evolve with new features and improvements across its various utility classes.

Spring Framework

Pros of Spring Framework

  • Comprehensive ecosystem for building enterprise Java applications
  • Extensive support for dependency injection and aspect-oriented programming
  • Active community and regular updates

Cons of Spring Framework

  • Steeper learning curve due to its complexity and extensive features
  • Larger footprint and potential performance overhead for smaller applications

Code Comparison

Spring Framework:

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

Guava:

List<String> names = Lists.newArrayList("John", "Jane", "Adam");
Predicate<String> startsWithJ = name -> name.startsWith("J");
List<String> filtered = names.stream().filter(startsWithJ).collect(Collectors.toList());

Spring Framework is a comprehensive Java application framework, while Guava is a set of core libraries and utilities. Spring offers a complete solution for building enterprise applications, including web services, security, and data access. Guava, on the other hand, focuses on providing utility classes and helper methods to enhance Java development.

Spring's dependency injection and AOP capabilities make it powerful for large-scale applications, but this comes with increased complexity. Guava is more lightweight and easier to integrate into existing projects, offering immediate benefits without significant architectural changes.

The code examples demonstrate Spring's annotation-based approach for creating RESTful endpoints, contrasting with Guava's focus on enhancing core Java functionalities like collections and predicates.

47,834

RxJava – Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.

Pros of RxJava

  • Specialized for reactive programming and asynchronous data streams
  • Powerful operators for composing and transforming observables
  • Better suited for complex event-driven applications

Cons of RxJava

  • Steeper learning curve due to reactive programming concepts
  • Can be overkill for simpler applications
  • Potential for memory leaks if not used correctly

Code Comparison

RxJava:

Observable.just(1, 2, 3, 4, 5)
    .filter(n -> n % 2 == 0)
    .map(n -> n * 2)
    .subscribe(System.out::println);

Guava:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> result = numbers.stream()
    .filter(n -> n % 2 == 0)
    .map(n -> n * 2)
    .collect(Collectors.toList());

Summary

RxJava excels in reactive programming scenarios, offering powerful tools for handling asynchronous data streams and complex event-driven applications. However, it comes with a steeper learning curve and may be excessive for simpler use cases.

Guava, on the other hand, provides a broader set of utilities for Java development, including collections, caching, and concurrency tools. It's generally easier to learn and use for everyday Java programming tasks but lacks the specialized reactive programming features of RxJava.

Choose RxJava for reactive, event-driven applications, and Guava for general-purpose Java development with enhanced utilities and collections.

14,240

Vert.x is a tool-kit for building reactive applications on the JVM

Pros of Vert.x

  • Designed for building reactive, scalable applications
  • Supports multiple programming languages (polyglot)
  • Built-in support for event-driven, non-blocking I/O operations

Cons of Vert.x

  • Steeper learning curve due to its reactive programming model
  • More complex setup and configuration compared to Guava
  • Smaller community and ecosystem compared to Guava

Code Comparison

Vert.x (Event-driven HTTP server):

Vertx vertx = Vertx.vertx();
vertx.createHttpServer().requestHandler(req -> {
  req.response().end("Hello World!");
}).listen(8080);

Guava (Using Optional):

Optional<String> optional = Optional.of("Hello World!");
String value = optional.orElse("Default Value");

Summary

Vert.x is a toolkit for building reactive, scalable applications, while Guava is a set of core libraries for Java. Vert.x excels in building high-performance, event-driven systems, whereas Guava provides utility classes and helper methods for common Java operations. The choice between them depends on the specific requirements of your project and your familiarity with reactive programming concepts.

33,257

Netty project - an event-driven asynchronous network application framework

Pros of Netty

  • Specialized for high-performance network programming
  • Asynchronous and event-driven architecture
  • Extensive protocol support (HTTP, WebSocket, SSL/TLS)

Cons of Netty

  • Steeper learning curve due to its complexity
  • More focused on networking, less general-purpose than Guava
  • Requires more boilerplate code for simple use cases

Code Comparison

Netty (server setup):

EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
 .channel(NioServerSocketChannel.class)

Guava (using collections):

List<String> list = Lists.newArrayList("a", "b", "c");
Set<String> set = Sets.newHashSet("x", "y", "z");
Map<String, Integer> map = Maps.newHashMap();

Summary

Netty excels in network programming with its high-performance, asynchronous architecture, while Guava offers a broader set of utilities for general Java development. Netty is more specialized and complex, whereas Guava provides simpler, more accessible tools for common programming tasks. Choose Netty for network-intensive applications and Guava for general-purpose Java development enhancements.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Guava: Google Core Libraries for Java

Latest release Build Status OpenSSF Best Practices

Guava is a set of core Java libraries from Google that includes new collection types (such as multimap and multiset), immutable collections, a graph library, and utilities for concurrency, I/O, hashing, primitives, strings, and more! It is widely used on most Java projects within Google, and widely used by many other companies as well.

Guava comes in two flavors:

Adding Guava to your build

Guava's Maven group ID is com.google.guava, and its artifact ID is guava. Guava provides two different "flavors": one for use on a (Java 8+) JRE and one for use on Android or by any library that wants to be compatible with Android. These flavors are specified in the Maven version field as either 33.3.0-jre or 33.3.0-android. For more about depending on Guava, see using Guava in your build.

To add a dependency on Guava using Maven, use the following:

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>33.3.0-jre</version>
  <!-- or, for Android: -->
  <version>33.3.0-android</version>
</dependency>

To add a dependency using Gradle:

dependencies {
  // Pick one:

  // 1. Use Guava in your implementation only:
  implementation("com.google.guava:guava:33.3.0-jre")

  // 2. Use Guava types in your public API:
  api("com.google.guava:guava:33.3.0-jre")

  // 3. Android - Use Guava in your implementation only:
  implementation("com.google.guava:guava:33.3.0-android")

  // 4. Android - Use Guava types in your public API:
  api("com.google.guava:guava:33.3.0-android")
}

For more information on when to use api and when to use implementation, consult the Gradle documentation on API and implementation separation.

Snapshots and Documentation

Snapshots of Guava built from the master branch are available through Maven using version HEAD-jre-SNAPSHOT, or HEAD-android-SNAPSHOT for the Android flavor.

  • Snapshot API Docs: guava
  • Snapshot API Diffs: guava

Learn about Guava

Links

IMPORTANT WARNINGS

  1. APIs marked with the @Beta annotation at the class or method level are subject to change. They can be modified in any way, or even removed, at any time. If your code is a library itself (i.e., it is used on the CLASSPATH of users outside your own control), you should not use beta APIs unless you repackage them. If your code is a library, we strongly recommend using the Guava Beta Checker to ensure that you do not use any @Beta APIs!

  2. APIs without @Beta will remain binary-compatible for the indefinite future. (Previously, we sometimes removed such APIs after a deprecation period. The last release to remove non-@Beta APIs was Guava 21.0.) Even @Deprecated APIs will remain (again, unless they are @Beta). We have no plans to start removing things again, but officially, we're leaving our options open in case of surprises (like, say, a serious security problem).

  3. Guava has one dependency that is needed for linkage at runtime: com.google.guava:failureaccess:1.0.2. It also has some annotation-only dependencies, which we discuss in more detail at that link.

  4. Serialized forms of ALL objects are subject to change unless noted otherwise. Do not persist these and assume they can be read by a future version of the library.

  5. Our classes are not designed to protect against a malicious caller. You should not use them for communication between trusted and untrusted code.

  6. For the mainline flavor, we test the libraries using OpenJDK 8, 11, and 17 on Linux, with some additional testing on newer JDKs and on Windows. Some features, especially in com.google.common.io, may not work correctly in non-Linux environments. For the Android flavor, our unit tests also run on API level 21 (Lollipop).