×

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

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

3N+1 problem program in Java

The 3N+1 problem is a hypothesis in the field of abstract mathematics (not yet proven). Collectively known as the Collatz problem. This tutorial will describe about the 3N+1 problem and...

3 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

Java For Loop

A for loop is used to execute a set of statements for a fixed number of times. It takes the following form: for (initialization; condition; update) { statements; } The for loop defines...

2 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

Java Math subtractExact() Method

The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long. Syntax: public static int subtractExact (int x,...

1 minute read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

How to Set Java_home in Linux

To set the Java_home in Linux, we must follow several steps to make us understand it easily.  Java follows the principle called WORA (write once run anywhere). We know that java...

3 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

How to Concatenate Two Strings in Java

How to Concatenate Two Strings in Java Concatenation of two strings means adding the beginning of one string to the end of the other string. Some of the ways to concatenate...

3 minutes read.