DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • Opportunities for Growth: Continuous Delivery and Continuous Deployment for Testers
  • Performance Comparison — Thread Pool vs. Virtual Threads (Project Loom) In Spring Boot Applications
  • Building the World's Most Resilient To-Do List Application With Node.js, K8s, and Distributed SQL
  • What Is JHipster?

Trending

  • Opportunities for Growth: Continuous Delivery and Continuous Deployment for Testers
  • Performance Comparison — Thread Pool vs. Virtual Threads (Project Loom) In Spring Boot Applications
  • Building the World's Most Resilient To-Do List Application With Node.js, K8s, and Distributed SQL
  • What Is JHipster?
  1. DZone
  2. Data Engineering
  3. Data
  4. HashMap – Single Key and Multiple Values Example

HashMap – Single Key and Multiple Values Example

Sometimes you want to store multiple values for the same hash key. The following code examples show you three different ways to do this.

Jagadeesh Motamarri user avatar by
Jagadeesh Motamarri
·
Oct. 26, 13 · Tutorial
Like (9)
Save
Tweet
Share
794.57K Views

Join the DZone community and get the full member experience.

Join For Free

Scenario

HashMap can be used to store key-value pairs. But sometimes you may want to store multiple values for the same key.

For example:

  • For Key A, you want to store - Apple, Aeroplane

  • For Key B, you want to store - Bat, Banana

  • For Key C, you want to store – Cat, Car

The following code snippets will show you three different ways of storing key-value pairs with a distinction of Single Key and Multiple Values.

HashMap – Single Key and Multiple Values Using List

package com.skilledmonster.examples.util.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * HashMap - Single Key and Multiple Values using List
 *
 * @author Jagadeesh Motamarri
 * @version 1.0
 */
public class SingleKeyMultipleValueUsingList {

    public static void main(String[] args) {

        // create map to store
        Map<String, List<String>> map = new HashMap<String, List<String>>();

        // create list one and store values
        List<String> valSetOne = new ArrayList<String>();
        valSetOne.add("Apple");
        valSetOne.add("Aeroplane");

        // create list two and store values
        List<String> valSetTwo = new ArrayList<String>();
        valSetTwo.add("Bat");
        valSetTwo.add("Banana");

        // create list three and store values
        List<String> valSetThree = new ArrayList<String>();
        valSetThree.add("Cat");
        valSetThree.add("Car");

        // put values into map
        map.put("A", valSetOne);
        map.put("B", valSetTwo);
        map.put("C", valSetThree);

        // iterate and display values
        System.out.println("Fetching Keys and corresponding [Multiple] Values n");
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            String key = entry.getKey();
            List<String> values = entry.getValue();
            System.out.println("Key = " + key);
            System.out.println("Values = " + values + "n");
        }
    }
}


HashMap – Single Key and Multiple Values Using Google Guava Collections

package com.skilledmonster.examples.util.map;

import java.util.Set;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

/**
 * HashMap - Single Key and Multiple Values using Google Guava Collections
 *
 * @author Jagadeesh Motamarri
 * @version 1.0
 */
public class SingleKeyMultipleValueUsingGuava {

    public static void main(String[] args) {

        // create multimap to store key and values
        Multimap<String, String> multiMap = ArrayListMultimap.create();

        // put values into map for A
        multiMap.put("A", "Apple");
        multiMap.put("A", "Aeroplane");

        // put values into map for B
        multiMap.put("B", "Bat");
        multiMap.put("B", "Banana");

        // put values into map for C
        multiMap.put("C", "Cat");
        multiMap.put("C", "Car");

        // retrieve and display values
        System.out.println("Fetching Keys and corresponding [Multiple] Values n");

        // get all the set of keys
        Set<String> keys = multiMap.keySet();

        // iterate through the key set and display key and values
        for (String key : keys) {
            System.out.println("Key = " + key);
            System.out.println("Values = " + multiMap.get(key) + "n");
        }

    }
}


HashMap – Single Key and Multiple Values Using Apache Commons Collection

package com.skilledmonster.examples.util.map;

import java.util.Set;

import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;

/**
 * HashMap - Single Key and Multiple Values using Apache Commons Collections
 *
 * @author Jagadeesh Motamarri
 * @version 1.0
 */
public class SingleKeyMultipleValueUsingApacheCollections {

    public static void main(String[] args) {

        // create multimap to store key and values
        MultiMap multiMap = new MultiValueMap();

        // put values into map for A
        multiMap.put("A", "Apple");
        multiMap.put("A", "Aeroplane");

        // put values into map for B
        multiMap.put("B", "Bat");
        multiMap.put("B", "Banana");

        // put values into map for C
        multiMap.put("C", "Cat");
        multiMap.put("C", "Car");

        // retrieve and display values
        System.out.println("Fetching Keys and corresponding [Multiple] Values n");

        // get all the set of keys
        Set<String> keys = multiMap.keySet();

        // iterate through the key set and display key and values
        for (String key : keys) {
            System.out.println("Key = " + key);
            System.out.println("Values = " + multiMap.get(key) + "n");
        }

    }
}

Output

The output for all the above three scenarios will be the same as the one below:

hashmap - single_key_multiple_values
Data structure

Published at DZone with permission of Jagadeesh Motamarri, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Opportunities for Growth: Continuous Delivery and Continuous Deployment for Testers
  • Performance Comparison — Thread Pool vs. Virtual Threads (Project Loom) In Spring Boot Applications
  • Building the World's Most Resilient To-Do List Application With Node.js, K8s, and Distributed SQL
  • What Is JHipster?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: