VOOZH about

URL: https://www.baeldung.com/guava-set-function-map-tutorial

⇱ Guava Set + Function = Map | Baeldung


πŸ‘ Image
eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
πŸ‘ announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
πŸ‘ announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
πŸ‘ announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
πŸ‘ announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
πŸ‘ announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
eBook – HTTP Client – NPI EA (cat=Http Client-Side)
πŸ‘ announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
πŸ‘ announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
πŸ‘ announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
πŸ‘ announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
πŸ‘ announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
πŸ‘ announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New β€œREST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
πŸ‘ announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
πŸ‘ announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
πŸ‘ announcement - icon

Refactor Java code safely β€” and automatically β€” with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β€” one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
πŸ‘ announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

In this tutorial – we will illustrate one of many useful features in Guavaβ€˜s collect package: how to apply a Function to a Guava Set and obtain a Map.

We’ll discuss two approaches – creating an immutable map and a live map based on the built-in guava operations and then an implementation of a custom live Map implementation.

2. Setup

First, we’ll add the Guava library as a dependency in pom.xml:

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

A quick note – you can check if there’s a newer version here.

3. The Mapping Function

Let’s first define the function that we’ll apply on the sets elements:

 Function<Integer, String> function = new Function<Integer, String>() {
 @Override
 public String apply(Integer from) {
 return Integer.toBinaryString(from.intValue());
 }
 };

The function is simply converting the value of an Integer to its binary String representation.

4. Guava toMap()

Guava offers a static utility class pertaining to Map instances. Among others, it has two operations that can be used to convert a Set to a Map by applying the defined Guava’s Function.

The following snippet shows creating an immutable Map:

Map<Integer, String> immutableMap = Maps.toMap(set, function);

The following tests asserts that the set is properly converted:

@Test
public void givenStringSetAndSimpleMap_whenMapsToElementLength_thenCorrect() {
 Set set = new TreeSet(Arrays.asList(32, 64, 128));
 Map<Integer, String> immutableMap = Maps.toMap(set, function);
 assertTrue(immutableMap.get(32).equals("100000")
 && immutableMap.get(64).equals("1000000")
 && immutableMap.get(128).equals("10000000"));
}

The problem with the created map is that if an element is added to the source set, the derived map is not updated.

4. Guava asMap()

If we use the previous example and create a map using the Maps.asMap method:

Map<Integer, String> liveMap = Maps.asMap(set, function);

We’ll get a live map view – meaning that the changes to the originating Set will be reflected in the map as well:

@Test
public void givenStringSet_whenMapsToElementLength_thenCorrect() {
 Set<Integer> set = new TreeSet<Integer>(Arrays.asList(32, 64, 128));
 Map<Integer, String> liveMap = Maps.asMap(set, function);
 assertTrue(liveMap.get(32).equals("100000")
 && liveMap.get(64).equals("1000000")
 && liveMap.get(128).equals("10000000"));
 
 set.add(256);
 assertTrue(liveMap.get(256).equals("100000000") && liveMap.size() == 4);
}

Note that the tests assert properly despite that we added an element through a set and looked it up inside the map.

5. Building Custom Live Map

When we talk of the Map View of a Set, we are basically extending the capability of the Set using a Guava Function.

In the live Map view, changes to the Set should be updating the Map EntrySet in real time. We will create our own generic Map, sub-classing AbstractMap<K,V>, like so:

public class GuavaMapFromSet<K, V> extends AbstractMap<K, V> {
 public GuavaMapFromSet(Set<K> keys, 
 Function<? super K, ? extends V> function) { 
 }
}

Worthy of note is that the main contract of all sub-classes of AbstractMap is to implement the entrySet method, as we’ve done. We will then look at 2 critical parts of the code in the following sub-sections.

5.1. Entries

Another attribute in our Map will be entries, representing our EntrySet:

private Set<Entry<K, V>> entries;

The entries field will always be initialized using the input Set from the constructor:

public GuavaMapFromSet(Set<K> keys,Function<? super K, ? extends V> function) {
 this.entries=keys;
}

A quick note here – in order to maintain a live view, we will use the same iterator in the input Set for the subsequent Mapβ€˜s EntrySet.

In fulfilling the contract of AbstractMap<K,V>, we implement the entrySet method in which we then return entries:

@Override
public Set<java.util.Map.Entry<K, V>> entrySet() {
 return this.entries;
}

5.2. Cache

This Map stores the values obtained by applying Function to Set:

private WeakHashMap<K, V> cache;

6. The Set Iterator

We will use the input Setβ€˜s iterator for the subsequent Mapβ€˜s EntrySet. To do this, we use a customized EntrySet as well as a customized Entry class.

6.1. The Entry Class

First, let’s see how a single entry in the Map will look like:

private class SingleEntry implements Entry<K, V> {
 private K key;
 public SingleEntry( K key) {
 this.key = key;
 }
 @Override
 public K getKey() {
 return this.key;
 }
 @Override
 public V getValue() {
 V value = GuavaMapFromSet.this.cache.get(this.key);
 if (value == null) {
 value = GuavaMapFromSet.this.function.apply(this.key);
 GuavaMapFromSet.this.cache.put(this.key, value);
 }
 return value;
 }
 @Override
 public V setValue( V value) {
 throw new UnsupportedOperationException();
 }
}

Clearly, in this code, we don’t allow modifying the Set from the Map View as a call to setValue throws an UnsupportedOperationException.

Pay close attention to getValue – this is the crux of our live view functionality. We check cache inside our Map for the current key (Set element).

If we find the key, we return it, else we apply our function to the current key and obtain a value, then store it in cache.

This way, whenever the Set has a new element, the map is up to date since the new values are computed on the fly.

6.2. The EntrySet

We will now implement the EntrySet:

private class MyEntrySet extends AbstractSet<Entry<K, V>> {
 private Set<K> keys;
 public MyEntrySet(Set<K> keys) {
 this.keys = keys;
 }
 @Override
 public Iterator<Map.Entry<K, V>> iterator() {
 return new LiveViewIterator();
 }
 @Override
 public int size() {
 return this.keys.size();
 }
}

We have fulfilled the contract for extending AbstractSet by overriding the iterator and size methods. But there’s more.

Remember the instance of this EntrySet will form the entries in our Map View. Normally, the EntrySet of a map simply returns a complete Entry for each iteration.

However, in our case, we need to use the iterator from the input Set to maintain our live view. We know well it will only return the Setβ€˜s elements, so we also need a custom iterator.

6.3. The Iterator

Here is the implementation of our iterator for the above EntrySet:

public class LiveViewIterator implements Iterator<Entry<K, V>> {
 private Iterator<K> inner;
 
 public LiveViewIterator () {
 this.inner = MyEntrySet.this.keys.iterator();
 }
 
 @Override
 public boolean hasNext() {
 return this.inner.hasNext();
 }
 @Override
 public Map.Entry<K, V> next() {
 K key = this.inner.next();
 return new SingleEntry(key);
 }
 @Override
 public void remove() {
 throw new UnsupportedOperationException();
 }
}

LiveViewIterator must reside inside the MyEntrySet class, this way, we can share the Setβ€˜s iterator at initialization.

When looping through GuavaMapFromSetβ€˜s entries using the iterator, a call to next simply retrieves the key from the Setβ€˜s iterator and constructs a SingleEntry.

7. Putting It All Together

After stitching together what we have covered in this tutorial, let us take a replace the liveMap variable from the previous samples, and replace it with our custom map:

@Test
public void givenIntSet_whenMapsToElementBinaryValue_thenCorrect() {
 Set<Integer> set = new TreeSet<>(Arrays.asList(32, 64, 128));
 Map<Integer, String> customMap = new GuavaMapFromSet<Integer, String>(set, function);
 
 assertTrue(customMap.get(32).equals("100000")
 && customMap.get(64).equals("1000000")
 && customMap.get(128).equals("10000000"));
}

Changing the content of input Set, we will see that the Map updates in real time:

@Test
public void givenStringSet_whenMapsToElementLength_thenCorrect() {
 Set<Integer> set = new TreeSet<Integer>(Arrays.asList(32, 64, 128));
 Map<Integer, String> customMap = Maps.asMap(set, function);
 
 assertTrue(customMap.get(32).equals("100000")
 && customMap.get(64).equals("1000000")
 && customMap.get(128).equals("10000000"));
 
 set.add(256);
 assertTrue(customMap.get(256).equals("100000000") && customMap.size() == 4);
}

8. Conclusion

In this tutorial, we have looked at the different ways that one can leverage Guava operations and obtain a Map view from a Set by applying a Function.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
πŸ‘ announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
πŸ‘ announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
πŸ‘ announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
πŸ‘ announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
πŸ‘ announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

πŸ‘ announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
πŸ‘ announcement - icon

Modern Java teams move fast β€” but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural β€” and as fast β€” as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)