Java 8 MultimapJava provides various useful built-in collection libraries. But sometimes we required special type of collections that are not in-built in Java's standard library. One of this collection is the Multimap. In this section, we will learn what is multimap and how to implement multimap in Java, and the Multimap interface of the Guava library. Java MultimapIn Java, Map is a data structure that allows us to map key to value. On the other hand, multimap is a new collection type found in the Guava library that allows the mapping of a single key to multiple values (like one-to-many relations in DBMS). But note that JDK does not allow multimapping. The alternative solution to implement multimap in Java by using Google's Guava library and Apache Commons Collections libraries. Both provides an implementation of the Multimap interface. It can store more than one value against a single key. Both the keys and values stored in the collection and considered as an alternative to Map<K, List<V>> or Map<K, Set<V>> (standard JDK Collections Framework). But using Multimap of Google's Guava library is not much helpful for us. Instead, we will implement our own Multimap class in Java that can also be customized accordingly. It is easy to write a Multimap class in Java. The following Java program depicts the implementation of the Multimap class in Java using Map and collection. Java Multimap ImplementationMultimapExample.java Output: ----- Printing Multimap using keySet ----- a: [Andrew] b: [Albert, Tom] d: [Sam, Reo] g: [Jack, David] Using Google's Guava LibraryMultimap<K, V> interface is defined in com.google.common.collect package of the Guava library. It implements many classes named as follows: ArrayListMultimap, ForwardingListMultimap, ForwardingMultimap, ForwardingSetMultimap, ForwardingSortedSetMultimap, HashMultimap, ImmutableListMultimap, ImmutableMultimap, ImmutableSetMultimap, LinkedHashMultimap, LinkedListMultimap, TreeMultimap. Syntax: A collection that maps keys to values (the same as in Map) but each key may be associated with multiple values. We can visualize the contents of a multimap either as a map from keys to nonempty collections of values. For example:
or
Java Multimap Interface Methods
Next TopicParallel Stream in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India