Guava ImmutableMultiset.copyOf() method in Java
In this post, we will explore how to use the Guava ImmutableMultiset.copyOf() method in Java to create an immutable multiset. We will also see some examples of how to use this method in different scenarios.
1. Usage of ImmutableMultiset.copyOf() method
An ImmutableMultiset is a type of multiset that cannot be modified in any way once it is created. No elements can be added or removed from it. Any attempt to do so will result in an UnsupportedOperationException. The ImmutableMultiset.copyOf() method is a static factory method that returns an immutable multiset containing the same mappings as a given multimap or iterable. The method has two overloaded versions:
- public static <K,V> ImmutableMultimap<K,V> copyOf(Multimap<? extends K,? extends V> multimap): This version takes a Multimap as an argument and returns an
ImmutableMultimapcontaining the same key-value pairs as theMultimap. The order of the keys and values in theImmutableMultimapfollows the “key-grouped” iteration order. - public static <E> ImmutableMultiset<E> copyOf(Iterable<? extends E> elements): This version takes an Iterable as an argument and returns an
ImmutableMultisetcontaining the same elements as the Iterable. The order of the elements in theImmutableMultisetfollows the “key-grouped” iteration order.
The copyOf() method performs a defensive copy of the given argument. This means that it creates a new immutable multiset object that is independent of the original argument. Any changes made to the original argument after calling copyOf() will not affect the returned immutable multiset.
2. Examples of ImmutableMultiset.copyOf() method
Let’s see some examples of how to use the ImmutableMultiset.copyOf() method in different scenarios.
Example 1: Creating an ImmutableMultiset from a Multimap
Suppose we have a Multimap that maps students to their grades in a course. We want to create an ImmutableMultimap that contains the same mappings as the Multimap, but is immutable and ordered. We can use the copyOf() method to achieve this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; class Main { public static void main(String[] args) { // Create a Multimap that maps students to their grades Multimap<String, Integer> studentGrades = HashMultimap.create(); studentGrades.put("Andrew", 90); studentGrades.put("Bob", 80); studentGrades.put("Christopher", 85); studentGrades.put("Andrew", 95); studentGrades.put("Bob", 75); // Create an ImmutableMultimap from the Multimap using copyOf() ImmutableMultimap<String, Integer> immutableStudentGrades = ImmutableMultimap.copyOf(studentGrades); // {Christopher=[85], Bob=[80, 75], Andrew=[90, 95]} System.out.println(immutableStudentGrades); } } |
We can see that the ImmutableMultimap contains the same key-value pairs as the Multimap, but is immutable and ordered by the “key-grouped” iteration order.
Example 2: Creating an ImmutableMultiset from an Iterable
Suppose we have an Iterable that contains some words. We want to create an ImmutableMultiset that contains the same words as the iterable, but is immutable and ordered. We can use the copyOf() method to achieve this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import com.google.common.collect.ImmutableMultiset; import java.util.List; class Main { public static void main(String[] args) { // Create an Iterable that contains some words Iterable<String> words = List.of("hello", "world", "hello", "guava", "world"); // Create an ImmutableMultiset from the Iterable using copyOf() ImmutableMultiset<String> immutableWords = ImmutableMultiset.copyOf(words); // Print the ImmutableMultiset System.out.println(immutableWords); // [hello x 2, world x 2, guava] } } |
We can see that the ImmutableMultiset contains the same words as the iterable, but is immutable and ordered by the “key-grouped” iteration order. The ImmutableMultiset also shows how many times each word appears in the iterable.
3. Benefits of using the copyOf() method
The copyOf() method has several advantages over other ways of creating immutable multisets. Some of them are:
- It is concise and expressive. You don’t need to use a builder to create an immutable multiset. You just need to pass the source as a parameter to the
copyOf()method and get the result. - It is safe and efficient. The
copyOf()method guarantees that the returned multiset is immutable and thread-safe. - It is consistent and predictable. The
copyOf()method preserves the order and the counts of the elements in the source. It also handlesnullelements gracefully by throwing aNullPointerException.
4. Conclusion
In this post, we have learned how to use the Guava ImmutableMultiset.copyOf() method in Java to create an immutable multiset from a multimap or an iterable. We have also seen some of the benefits of using this method, such as thread-safety, memory-efficiency, consistency, and order.
If you are interested in learning more about this method, you can check out the Guava official website or its GitHub repository.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)