Here is what I have:
HashMap<String,HashMap<Integer,Integer>> data =
new HashMap<String,HashMap<Integer,Integer>>();
But I am having trouble adding values to this, because the inner hashmap doesn't have a name (note: it isn't supposed to). I'm actually trying to add an array list to the first Integer in HashMap So I am trying something like:
data.put(var, data.get(array.get(x), y));
Which it very much doesn't like and I'm totally clueless as to how to do it.
Note that
HashMap<String,HashMap<Integer,Integer>> data =
new HashMap<String,HashMap<Integer,Integer>>();
only creates the "outer" HashMap instance. After this statement you have an empty HashMap that takes Strings as keys and HashMap<Integer, Integer> as value.
You can add an instance of HashMap<Integer, Integer> to data with this:
data.put("myKey", new HashMap<Integer, Integer>());
After that you can add Integer values to the second HashMap:
data.get("myKey").put(123, 456); // use 123 as key and 456 as value
Get the values back:
data.get("myKey").get(123); // returns 456
You have to get the inner hash map first:
HashMap<Integer,Integer> innerData = data.get(var);
Then you can put your value into it:
innerData.put(x, y);
Just do it like this:
data.put( var, new HashMap(intKey, intVal));
where intKey and intVal are Integer type Key and Integer type value.
HashMap<String,HashMap<Integer,Integer>> data =
new HashMap<String,HashMap<Integer,Integer>>();
((Map)data.get( "keyname" )).get(1);
and subsequently:
((Map)data.get( "keyname" )).get( 1 ).put(2);
Related
So I essentially want to go through all the elements in the arraylist and match it with the keys of each hashmap and for the values of the common keys I want to make a new arraylist.
Essentially if keygrades is on value 1, I want to check every hashmap with the key 1 and then extract all the values associated with that key and make a brand new arraylist with those values.
ArrayList <String> keygrades = new ArrayList<>();
HashMap <String,String> gradeA = new HashMap<>();
HashMap <String,String> gradeB = new HashMap<>();
HashMap <String,String> gradeC = new HashMap<>();
HashMap <String,String> gradeD = new HashMap<>();
This is what is in the hashmap:
keygrades = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
gradeA = {11=134, 1=100, 3=110, 4=120, 15=142, 5=130}
gradeB = {2=102, 3=103, 6=108, 8=109}
gradeC = {3=104, 5=105, 6=111}
gradeD = {3=122, 4=123}
For example for key 1 I want a new arraylist which would be (100,"","","") ""= empty string. For key 2 I want a new arraylist which would be ("",102,"","").It would continue going through hashmaps in order and inputting into new arraylist each time.
I recommend writing a method with this struture:
Create an ArrayList<ArrayList>, which will hold the outcoming
ArrayLists containing the different values for common keys.
Iterate over Arraylist containing the keys.
Create an ArrayList that will get the 4 values.
Check all 4 Hashmaps with the current key using HashMap.get(key).
If the outcome is null, you should add "" to your ArrayList, otherwise you
enter the value to the ArrayList inside the loop.
After it iterated through the ArrayList containing the keys. You should have an
ArrayList<ArrayList> holding exactly as much ArrayList containing the values for similar keys, as you ArrayList of keys size.
You can achieve this by transforming your maps into a stream of maps and extracting the values for a particular key.
List<String> values = Stream.of(gradeA,
gradeB,
gradeC,
gradeD)
.map(map -> map.getOrDefault("1", ""))
.collect(Collectors.toList());
To reuse this, you'll have to create a function that handles the combining of the maps and a function that extracts values from that stream of maps.
The example should get you on your way.
I'm new to Java and I'm struggling to figure out something trivial.
I have a HashMap with keys of type String and values of type ArrayList <String>, and it returns something like this:
dict = {Color=[Blue, Purple]}
I'm struggling to figure out how I can grab a specific element from the array in the value of dict. Like if I got dict.value[0], it would return the string 'Blue'.
I've tried doing:
Object values = dict.values().toArray[0];
and I assumed that since I changed it to an array, I could do something like values.get(0) to get the first element, but that doesn't work because values is type Object. Any ideas on how to resolve this?
if your HashMap is like:
Map<String, List<String>> myColorsMap = new HashMap<>();
And after populating the map is like:
{Red=[firstRed, secondRed, thirdRed], Blue=[firstBlue, secondBlue, thirdBlue]}
then you can retrieve Blue's key value (a List) like:
String blueFirstElement = myColorsMap.get("Blue").get(0); // --> will give first element of List<String> stored against Blue key.
To get collection of all keys in your map (or "dictionary"):
myColorsMap.keySet();
will give:
[Red, Blue]
When you do:
Object values = dict.values().toArray[0];
First, this is wrong. What you were trying to do is this:
Object values = dict.values().toArray();
Which returns Object[] and it is ambiguous. No need to do that. Java's Map interface and HashMap implementation have a lot of utility methods for you to iterate and retrieve your values.
First, use .get() on map to get the ArrayList using key
List<String> colors = dict.get("Color");
Then use .get() on list to get the element using index
String color = colors.get(0);
You can do this in one line this way
String color = dict.get("Color").get(0);
You are trying with dict.values().toArray[0] which is wrong syntax thats the problem. dict.values() will return Collection<List<String>>, you can get List of values this way
List<List<String>> listOfValues = new ArrayList<>(colorsMap.values());
Then you can access each value by index using .get()
List<String> colors = listOfValues.get(0);
Note : HashMap don't store any order.
Cast to type of java.util.List, and then you can get value through index.
#SuppressWarnings("unchecked")
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<>(2);
map.put("color", Arrays.asList("blue", "yellow", "green", "white"));
map.put("size", Arrays.asList("small", "medium", "large"));
List<String> o = (List<String>) map.values().toArray()[0];
System.out.println(o.get(0)); //output is 'blue'
List<String> s = (List<String>) map.values().toArray()[1];
System.out.println(s.get(1)); //output is 'medium'
}
This question already has answers here:
HashMap: One Key, multiple Values
(15 answers)
Closed 2 years ago.
My problem is that I have an Hashtable and I end up with some key having two values. I would like to get both of these value, so I can see which one I want and take it.
Here is an exemple :
Hashtable<String, String> myTable = new Hashtable<>();
myTable.put("key1", "value1");
myTable.put("key1", "value2");
System.out.println(myTable.get("key1"));
//output : value2
How to retrieve both of the value ?
Thank you for your help !
EDIT :
In my tests, the HashTable can't store 2 values like this but I assure that in my project where I have a (I believe) code that does the same thing. When, after my algorithm has ran I System.out.prinln(myTable) it does show multiple time the same key with differents value.
It depends on the way to create a HashTable, in your example. You create a HashTable maps a String to a String, then because the value is a String, you cannot expect the table can store multiple values on one key. When you do the second put method, it will find the key with value key1 and replace the previous value which is mapped to this key to the new one.
If you want to store multiple values on one key, think about the list which will hold multiple values for your key. Here is an example to map a key with a type of String to multiple String values:
Hashtable<String, ArrayList<String>> myTable = new Hashtable<>();
ArrayList<String> listValue = new ArrayList<>();
listValue.add("value1");
listValue.add("value2");
myTable.put("key1", listValue);
System.out.println(myTable.get("key1")); // get all values of the key [value1, value2]
System.out.println(myTable.get("key1").get(0)); // get the first value of this key, value1
System.out.println(myTable.get("key1").get(1)); // get the second value of this key, value2
It is recommended to use HashMap over a HashTable.
In HashMap class, put function adds object if it isn't exist, if it's exist just updates the value. You can create another class to keep values;
class exampleValue {
String v1, v2;
exampleValue() {}
}
and
HashMap<String, exampleValue> h = new HashMap<>();
exampleValue v = new exampleValue();
v.v1 = "a";
v.v2 = "b";
h.put("key", v);
h.get("key").v1; //returns "a"
h.get("key").v2; //returns "b"
I am new in java arraylist. I have difficulties in creating arraylist. This is the example below. s1,s2,s3,s4,s5 is the category for people to choose and add number into it,
{[s1,0]}
{[s2,0]}
{[s3,0]}
{[s4,0]}
{[s5,0]}
For example, s1:2, s2:3, s1:3, s5:4, s3:2. How can i make the output to become like this
{[s1,5]}
{[s2,3]}
{[s3,2]}
{[s4,0]}
{[s5,4]}
I hope that someone can help me in this.
What you need here is a map. For example Map<String, Integer> map = new HashMap<String, Integer>();. Then to add you would do the following map.put("s1", 1);. An ArrayList is just an implementation of a list backed by an array and as such cannot have a key value pair. In order to update a value you would just do this:
int current = map.get("s1");
map.put("s1", current++);
If you need to track many values by a key then you would instead have a map of ArrayList, declared like so:
Map<String, ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();
ArrayList<Integer> s1sValues = new ArrayList<Integer>();
s1s.add(1);
s1s.add(2);
map.put("s1", s1sValues);
//To add to existing
map.get("s1").add(3);//If you don't already have a reference
s1sValues.add(4);//If you do have the reference.
`
Lets say I have hashmap store and it contains for example-(11,name1) (11,name2) and i call HashMap.get(11), it only shows name2 which means it overrides the first input for 11. How can i store both name1 and name2 with ID 11 using hashmap?I know i can use both HashMap and HashSet but i dont want to create every HashSet for HashMap. I just want to use hashSet only. how should I do this? I hope you can help me with it. Thank you.
public void insert(int ID, String key){
int hashKey = Hash(key);
System.out.println("Hash Key" + hashKey);
int node = Find(ID,hashKey);
storeR.put(node, key);
}
You can use:
HashMap<Integer, List<String>>
In HashMap you must put a value with every key. So of course, if you put the same key twice, the value will be override.
The solution is to hold a collection of values for every key.
in your code instead of:
storeR.put(node, key);
you should write:
List<String> nodeValues = storeR.get(node);
if (nodeValues == null) {
nodeValues = new ArrayList<String>();
storeR.put(node, nodeValues );
}
nodeValues.add(key);
And you should also change storeR type to be HashMap<Integer, List<String>>
MultiMap is also a similar solution.
You can probably use MultiMap from Apache Commons Collections.
You will have to either have a HashMap where the value of each key is another collection (list or set) or concatenate the string values together (e.g. comma separated).
Alternatively you may be able to find a data collection that supports multiple values per key.
To store multiple values for a single key, use a HashMap that contains a list as a value. HashMap's implementation overrides values for existing keys.
HashMap<Integer,List<String>>
Also, you could use MultiMap from Apache Commons or, if you're just using Integer I can suggest you use an array directly:
List<String>[] yourList = new List<String>[initCapacity];
So you can access that list like this:
yourList[0].add("A New Value");
As a final note, you can use any collection you deem appropiate, even a HashSet if performance is important for you and you won't store duplicated values for a same index.