×

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

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

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...

7 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 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.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.