How to Store More Than One String in a Map

HashMap with multiple values under the same key

You could:

  1. Use a map that has a list as the value. Map<KeyType, List<ValueType>>.
  2. Create a new wrapper class and place instances of this wrapper in the map. Map<KeyType, WrapperType>.
  3. Use a tuple like class (saves creating lots of wrappers). Map<KeyType, Tuple<Value1Type, Value2Type>>.
  4. Use mulitple maps side-by-side.


Examples

1. Map with list as the value

// create our map
Map<String, List<Person>> peopleByForename = new HashMap<>();

// populate it
List<Person> people = new ArrayList<>();
people.add(new Person("Bob Smith"));
people.add(new Person("Bob Jones"));
peopleByForename.put("Bob", people);

// read from it
List<Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs[0];
Person bob2 = bobs[1];

The disadvantage with this approach is that the list is not bound to exactly two values.

2. Using wrapper class

// define our wrapper
class Wrapper {
public Wrapper(Person person1, Person person2) {
this.person1 = person1;
this.person2 = person2;
}

public Person getPerson1() { return this.person1; }
public Person getPerson2() { return this.person2; }

private Person person1;
private Person person2;
}

// create our map
Map<String, Wrapper> peopleByForename = new HashMap<>();

// populate it
peopleByForename.put("Bob", new Wrapper(new Person("Bob Smith"),
new Person("Bob Jones"));

// read from it
Wrapper bobs = peopleByForename.get("Bob");
Person bob1 = bobs.getPerson1();
Person bob2 = bobs.getPerson2();

The disadvantage to this approach is that you have to write a lot of boiler-plate code for all of these very simple container classes.

3. Using a tuple

// you'll have to write or download a Tuple class in Java, (.NET ships with one)

// create our map
Map<String, Tuple2<Person, Person> peopleByForename = new HashMap<>();

// populate it
peopleByForename.put("Bob", new Tuple2(new Person("Bob Smith",
new Person("Bob Jones"));

// read from it
Tuple<Person, Person> bobs = peopleByForename["Bob"];
Person bob1 = bobs.Item1;
Person bob2 = bobs.Item2;

This is the best solution in my opinion.

4. Multiple maps

// create our maps
Map<String, Person> firstPersonByForename = new HashMap<>();
Map<String, Person> secondPersonByForename = new HashMap<>();

// populate them
firstPersonByForename.put("Bob", new Person("Bob Smith"));
secondPersonByForename.put("Bob", new Person("Bob Jones"));

// read from them
Person bob1 = firstPersonByForename["Bob"];
Person bob2 = secondPersonByForename["Bob"];

The disadvantage of this solution is that it's not obvious that the two maps are related, a programmatic error could see the two maps get out of sync.

Storing multiple datatypes in a single HashMap

You can instantiate an array in java by doing

someMap.put("OptionId", new int[]{7,8,8});

Otherwise you will need a function that returns those values in an array.

For your case: if you want to create a HashMap of multiple datatypes you can use

HashMap<String, Object> map = new HashMap<String, Object>();

You can then put anything you want in

map.put("key1", "A String");
map.put("key2", new int[]{7,8,8});
map.put("key3", 123);

Except now the tricky part is you don't know what is what so you need to use instanceof to parse the map unless you know what type of object is at a key then you can just cast it to that type.

if(map.get("key1") instanceof String)
String s = (String) map.get("key1"); // s = "A String"

or

int[] arr = (int[]) map.get("key2"); // arr = {7,8,8}

How to store more than one value for same key in HashMap?

Create a class InputRow:

class InputRow {

private int value1;
private String value2;
private int value3;

//...getters and setters

}

and a HashMap<Integer, List<InputRow>>. The hash map key is your row index and you assign all matching rows as a List<InputRow> to the hash map.

For clarification, a HashMap stores one entry for one unique key. Therefore, you cannot assign more than one entry to the same key or else the entry will just be overwritten. So, you need to write a container to cover multiple objects or use an existing like List.

Example for your code

I used both of your text fragments, separated by a newline character, so two lines. This snippet puts two InputRow objects in a list into the HashMap with the key "InputRow". Note, that the matcher group index starts at 1, zero refers to the whole group. Also mind that for simplicity I assumed you created a InputRow(String, String, String) constructor.

String line = "1,Kit,23\n2,Ret,211";

final Map<String, List<InputRow>> regexResults = new HashMap<>();
Pattern pattern = Pattern.compile("(.+),(.+),(.+)");
final Matcher matcher = pattern.matcher(line);

List<InputRow> entry = new ArrayList<>();

while (matcher.find()) {
entry.add(new InputRow(matcher.group(1), matcher.group(2), matcher.group(3)));
}

regexResults.put("InputRow", entry);

C++11 Simplest way to store multiple data types for value(int and string) in map key, value ?

In c++17, you may use std::variant<int, std::string>, prior to this, you may use the one from boost:

using IntOrString = std::variant<int, std::string>;
std::map<std::string, IntOrString> myMap;
myMap["first_key"] = 10;
myMap["second_key"] = "stringValue";

Java HashMap - How to Create third parameters to store my user amount

You cannot have multiple values corresponding to a single key. What you can however do is have a nested Hashmap. In that map you can have further user details , such as user name , user address , user balance and so on.

Map<String, HashMap<String,String>> map = new HashMap<>();
map.put("123456789" , new HashMap<>());
map.put("987654321" , new HashMap<>());
map.get("123456789").put("pin number" , "123456");
map.get("123456789").put("phone number" , "0000000000");
map.get("123456789").put("name" , "xyz");
map.get("123456789").put("balance" , "20000");
map.get("987654321").put("pin number" , "654321");
map.get("987654321").put("phone number" , "1111111111");
map.get("987654321").put("name" , "zyx");
map.get("987654321").put("balance" , "10000");

So the map looks like this ->

{123456789 = { pin number = 123456, balance = 20000 , name = xyz , phone number = 0000000000} , 987654321 = { pin number = 654321 , balance = 10000 , name = zyx, phone number = 1111111111}}

Now for each account number you can store multiple types of values.
To get values corresponding to account number use,

 String actualPin = map.get(card).get("pin number");

map.get(card) will return you the map corresponding to that card account number. And inside that map you can get all of the values you want via the String keys inside that map.
Hope this helps.

Java how to store more than one string variable

I hope I understand your problem correct: your problem is that you overwrite your old entries? To prevent that you have to use some kind of array or list.

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader input = new BufferedReader(reader);

String inputValues;
String[] person;
List<String> lastname = new ArrayList<String>();
List<String> firstname = new ArrayList<String>();
List<String> id = new ArrayList<String>();

while(true){
inputValues = input.readLine();
person = inputValues.split("\\s+");
if(inputValues.equals("exit")){
break;
}else{
lastname.add(person[0]);
firstname.add(person[1]);
id.add(person[2]);
}
}

for(int i=0; i<lastname.size(); i++)
System.out.println(firstname.get(i) +" "+ lastname.get(i) +" ("+ id.get(i) +")");
}
}

See here: https://ideone.com/l1TnF8



Related Topics



Leave a reply



Submit