×

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

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

ConcurrentSkipListSet in Java

ConcurrentSkipListSet is a class that is a part of collection framework in Java.It has been available since Java version 1.6. ConcurrentSkipListSet  is a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap.The...

16 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.