Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Consumer types: An Introduction to Guava

Header Image

Ahoy matey! Ye be lookin’ to learn about consumer types in Guava, eh? Well, ye be in luck, for I’ve got all the information ye need to know about this swashbuckling topic!

So what exactly are consumer types? In simple terms, a consumer is a functional interface in Java that takes in a single argument and doesn’t return anything. It’s often used to perform some kind of operation on an object, such as modifying its state or printing its contents.

Guava, being the handy toolkit that it is, provides its own set of consumer types that offer additional functionality beyond the standard Java consumer. These types include:

  • Consumer: The basic Guava consumer type, which takes in a single argument and performs some kind of operation on it.
  • BiConsumer: A consumer type that takes in two arguments and performs some kind of operation on them.
  • ObjDoubleConsumer: A consumer type that takes in an object and a double value and performs some kind of operation on them.
  • ObjIntConsumer: A consumer type that takes in an object and an integer value and performs some kind of operation on them.
  • ObjLongConsumer: A consumer type that takes in an object and a long value and performs some kind of operation on them.

These consumer types can be used in a variety of contexts, from manipulating collections to performing complex data transformations. Let’s take a closer look at how they work.

Usage of Guava Consumer Types

When using Guava consumer types, the first step is to define the type of consumer you want to use. For example, let’s say you have a list of strings that you want to print to the console. Here’s how you could define a basic consumer to achieve this:

Consumer<String> printConsumer = str -> System.out.println(str);

This creates a new consumer that takes in a string and prints it to the console. Now you can use this consumer to print out all the strings in your list:

List<String> strings = ImmutableList.of("Ahoy", "Matey", "Avast");
strings.forEach(printConsumer);

This will print out each string in the list to the console, one after the other. Easy as pie!

But that’s just the beginning. You can use Guava consumer types to perform all kinds of operations on objects. For example, let’s say you have a map of integers to strings, and you want to print out each key-value pair in the map. Here’s how you could define a bi-consumer to achieve this:

BiConsumer<Integer, String> printMapConsumer = (key, value) -> System.out.println(key + ": " + value);

This creates a new bi-consumer that takes in an integer key and a string value, and prints them out in a formatted string. Now you can use this consumer to print out all the key-value pairs in your map:

Map<Integer, String> map = ImmutableMap.of(1, "Ahoy", 2, "Matey", 3, "Avast");
map.forEach(printMapConsumer);

This will print out each key-value pair in the map to the console, in the format “key: value”.

Conclusion

And that, me hearties, is a basic introduction to Guava consumer types. As ye can see, they can be a powerful tool for performing all kinds of operations on objects, from printing to modifying to transforming. So if ye be lookin’ to add some extra functionality to yer Java code, give Guava consumer types a try! Arrrr!

Examples of using Consumer Types

Now that we’ve covered the basics of Guava consumer types, let’s dive into some examples of how they can be used in practice.

Example 1: Modifying Collection Elements

Let’s say you have a list of integers, and you want to square each integer in the list. Here’s how you could use a consumer to achieve this:

List<Integer> numbers = ImmutableList.of(1, 2, 3, 4, 5);
Consumer<Integer> squareConsumer = num -> num = num * num;
numbers.forEach(squareConsumer);

This will modify each element in the list to be its square. Note that in this case, we’re using a basic consumer rather than a bi-consumer, since we only need to modify a single value.

Example 2: Grouping Collection Elements

Let’s say you have a list of strings, and you want to group them by length. Here’s how you could use a bi-consumer to achieve this:

List<String> strings = ImmutableList.of("ahoy", "matey", "avast", "ye", "landlubber");
Map<Integer, List<String>> groups = new HashMap<>();
BiConsumer<Integer, String> groupConsumer = (length, str) -> {
    if (!groups.containsKey(length)) {
        groups.put(length, new ArrayList<>());
    }
    groups.get(length).add(str);
};
strings.forEach(str -> groupConsumer.accept(str.length(), str));

This will group the strings by their length, resulting in a map where the keys are the lengths of the strings and the values are lists of strings with that length.

Example 3: Performing Complex Transformations

Let’s say you have a list of users, and you want to convert each user’s name to uppercase and then print it to the console. Here’s how you could use a combination of a function and a consumer to achieve this:

List<User> users = ImmutableList.of(new User("Jack"), new User("Sparrow"), new User("Will"));
Function<User, String> upperNameFunction = user -> user.getName().toUpperCase();
Consumer<String> printConsumer = str -> System.out.println(str);
users.stream().map(upperNameFunction).forEach(printConsumer);

This will convert each user’s name to uppercase using the function, and then print it to the console using the consumer. Note that in this case, we’re using a stream rather than a for-each loop, since we need to perform a transformation on each element in the list before printing it.

And that, me hearties, is a brief overview of how to use Guava consumer types in your Java code. As ye can see, they can be a powerful tool for performing all kinds of operations on objects, from modifying to grouping to transforming. So if ye be lookin’ to add some extra functionality to yer Java code, give Guava consumer types a try! Arrrr!