×

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one of these items. In this section, we'll learn what multimap is, how to use it in Java, and how the Guava library's Multimap interface works.

Java Multimap

A data structure called Map in Java enables us to map a key to a value. On the other hand, the Guava library has a brand-new collection type called multimap that can map a single key to a number of values. But keep in mind that JDK does not support multimapping.

The alternative method for implementing multimap in Java makes use of the Apache Commons Collections and Google's Guava libraries. Both offer a Multimap interface implementation. With a single key, it can hold several values. The collection's keys and values are both kept in storage as an alternative to MapK, ListV or MapK, SetV. (standard JDK Collections Framework).

However, we don't really benefit much from the Guava library's Multimap feature. Instead, we'll create a new Multimap class in Java that may be adjusted as needed. In Java, creating a Multimap class is simple.

The Multimap class is implemented in Java using Map and collection in the following Java application.

Implementations

As always, favourImmutableListMultimap and ImmutableSetMultimap for immutable implementations. The list of "All Known Implementing Classes" above includes general-purpose mutable implementations. Alternatively, you can use the Multimaps.newMultimap set of methods to build a custom multimap supported by any Map and Collection type. Finally, using Multimaps.index is a common method of obtaining a multimap. For these and additional static multimap functions, see the Multimaps class.

// java program for java multimap implementation

import java.util.*; 


class MM<Y, E>


{ 


//putting together a key-value map


private M<Y, Collection<E>> m = new HashMap<>();  


//In this multimap, add the specified value to the specified key.


public void put(Y key, Eval) 


{ 


if (m.get(key) == null)  


{ 


m.put(key, new ArrayList<E>()); 


} 


m.get(key).add(val); 


} 


//if the specified key isn't already connected to a value, connect it to the specified value.


public void putIA(Y key, Eval) 


{ 


if (m.get(key) == null)  


{ 


m.put(key, new ArrayList<>()); 


} 


// Insert the value if it's missing.


if (!m.get(key).contains(val))  


{ 


m.get(key).add(val); 


} 


} 


//If the key is not mapped to any values in this mm, the method returns null, otherwise it returns a collection of values for which the given key is mapped.


public Collection<E> get(Object key)  


{ 


return m.get(key); 


} 


//Using this multimap's keys as input, the method returns a set view of them.


public Set<Y>keySet()  


{ 


return m.keySet(); 


} 


//Using this multimap's keys as input, the method returns a set view of them.


public Set<M.Entry<Y, Collection<E>>>entrySet()  


{ 


return m.entrySet(); 


} 


//Using this multimap's values as input, the method returns a Collection view of Collection.


public Collection<Collection<E>> values()  


{ 


return m.values(); 


} 


//returns true if there is a mapping for the given key in this multimap.


public booleancontainsKey(Object key)  


{ 


return m.containsKey(key); 


} 


//Removes the key's mapping from this multimap if it is present and returns the key's previous values as a collection, or null if the key's mapping was absent.


public Collection<E> remove(Object key)  


{ 


return m.remove(key); 


} 


//this multimap's total number of key-value mappings is returned.


public int s() 


{ 


int s = 0; 


for (Collection<E> value: m.values())  


{ 


s += value.s(); 


} 


return s; 


} 


//returns true if there are no key-value mappings in this multimap.


public booleanisE()  


{ 


return m.isE(); 


} 


//Deletes every mapping from this multimap.


public void clear()  


{ 


m.clear(); 


} 


//only removes the entry for the key specified if it is currently mapped to the value specified, and if it is removed, it returns true.


public boolean remove(Y key, Eval) 


{ 


if (m.get(key) != null) // key exists 


return m.get(key).remove(val); 


return false; 


} 


//Replaces the entry for the given key only if it is already mapped to the given value, and returns true if it has been replaced.


public boolean replace(Y key, EoldVal, EnewVal) 


{ 


if (m.get(key) != null) 


{ 


if (m.get(key).remove(oldVal))  


{ 


return m.get(key).add(newVal); 


} 


} 


return false; 


} 


} 


//main class 


public class ME 


{ 


//main method 


public static void main(String args[]) 


{ 


//Creating a multimap of type String 


MM<String, String> mm = new MM(); 


//increasing the multimap's value


mm.put("x", "jhon"); 


mm.put("y", "siri"); 


mm.put("y", "alexa"); 


mm.put("z", "Sam"); 


mm.put("z", "leo"); 


mm.put("a", "sony"); 


mm.put("a", "tom"); 


System.out.println("----- Printing Mm using keySet -----\n"); 


//loop iterates over mm 


for (String lastName: mm.keySet())  


{ 


//printing key and val


System.out.println(lastName + ": " + mm.get(lastName)); 


} 


} 


}

Output:

Printing Mm using keySet 
x: [jhon] 
y: [siri, alexa] 
z: [Sam, leo] 
a: [sony, tom]

NOTE: Although the majority of multimaps are implemented using the first interpretation, the Multimap API was created using the second type. The size() is therefore 3, not 2, and the values() collection is [1, 2, 3], not [[1, 2], [3]], using the multimap displayed above as an example. Use the multimap's asMap() view (or make a MapK, CollectionV>> in the first place) when the first approach is more practical.

Sub Interfaces:

ListMultimap and SetMultimap are preferable to utilising the Multimap interface directly. These derive their names from the fact that the collections they return from get behave similarly to List and Set, respectively, and of course implement those types of collections.

For instance, the code sample for "presidents" utilised a ListMultimap; if it had been a SetMultimap, two presidents would have disappeared, and last names might or might not have appeared chronologically.

Using Google's Guava Library

The Guava library's com.google.common.collect package contains the definition of the Mm Y, E> interface. It implements a number of the following classes:

LinkedHashMultimap, LinkedListMultimap, TreeMultimap, ArrayListMultimap, ForwardingListMultimap, ForwardingMultimap, ForwardingSetMultimap, ForwardingSortedSetMultimap, HashMultimap, ImmutableListMultimap, ImmutableMultimap, and ImmutableSetMultimap

Syntax:

Public interface Mm <Y, E>

a collection that, like a map, maps keys to values, but where keys might have numerous values associated with them. A map from keys to nonempty collections of values can be used to represent the contents of a multimap. For instance:

A → 1, 2

B → 3

or

A → 1

A → 2

B → 3

Java Multimap Interface Methods

MethodDescription
putAll(Multimap< extends Y, extends E> multimap)In the order returned by multimap.entries, it stores all key-value pairs from multimap in this multimap ().
Values ()Without collapsing duplicates (so values are unique), it returns a view collection containing the value from each key-value pair present in this multimap (). Size() equals Size().
asMap ()It gives back a representation of this multimap as a Map from each unique key to the nonempty collection of values connected to that key.
Clear()It clears the multimap of all key-value pairs, leaving it empty.
ContainsEntry( object key,                          Object val)If this multimap has at least one key-value pair that includes both the key and the value, it returns true.
containsKey ( object key)If there are at least one key-value pair with the key in this multimap, it returns true.
containsValue(Object val)If this multimap has at least one key-value pair with the value, it returns true.
Entries ()All key-value pairs found in this multimap are returned as a view collection of Map.Entry instances.
Equals (object obj)It determines whether the supplied object and this multimap are equal.
forEach(BiConsumer< super Y, super E> action)It executes the specified action on each key-value pair in this multimap.
Get ( Y key)If any values are connected to the key in this multimap, it produces a view collection of those values.
Hashcode ()It gives the multimap's hash code back.
isEmpty ()If this multimap doesn't include any key-value pairs, it returns true.
Keys ()Without compressing duplicates, it returns a view collection that has the key from each key-value pair in this multimap.
Keyset ()It gives back a view collection with all the unique keys in this multimap.
put(Y key, E value)a key-value pair is kept in this multimap.
putAll(Y key, Iterable< extends E> values)For each value, it stores a key-value pair in this multimap using the same key, key.
remove(Object key, Object val)If there is a single key-value pair in this multimap containing the key and the value, it is removed.
removeAll(Object key)It eliminates all key-related values.
replaceValues(Y key, Iterable< extends E>val)It replaces any pre-existing values for a key by storing a collection of values with the same key.
Size ()This multimap returns the number of key-value pairs it contains.

Related Topics

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

How to Convert String to long in Java

How to Convert String to long in java It is used when you want to perform the mathematical operation on the String which contains long number then the conversion from String...

4 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.