HashMap - Adding a value to a specific item [duplicate] - java

This question already has answers here:
How to update a value, given a key in a hashmap?
(17 answers)
Closed 11 months ago.
public void addItem(String itemName,int numItemAdd) {
HashMap <String,Integer> items = new HashMap<String,Integer>();
int totalval;
totalval =+ numItemAdd;
items.put(itemName,totalval);
}
I am new to HashMaps. I am wanting to add the integers to the specific itemName. For example, addItem("socks",100); addItem("socks",200). Whenever I do this, instead of getting 300 I only get 200. I know that put() replaces the last value used, but I do not know how to add the numbers so that I can get 300 instead of having the last value used.

You can try this, it also manages the case when socks don't exist:
private HashMap <String,Integer> items = new HashMap<String,Integer>();
public static void main(String[] args) {
Test test = new Test();
test.addItem("socks", 100);
test.addItem("socks", 200);
}
public void addItem(String itemName,int numItemAdd) {
items.put(itemName,items.get(itemName) != null ? (items.get(itemName) + numItemAdd) : numItemAdd);
System.out.println("Socks value:" + items.get(itemName));
}

Related

Adding values under same key HashMap in Java [duplicate]

This question already has answers here:
Increment an Integer within a HashMap
(13 answers)
Closed 10 months ago.
I'm new to HashMaps, and I was wondering if there was a way to add values together if they have the same key.
For example, when I have the key 'a' and the value is 20 and later on I use the key 'a' again and the value is 10 the value should now be 30.
I don't know how I would check if the Value already is in the HashMap and then use the same value again. The adding part could be done with just a variable that copies the current value and adds the new one, I guess.
I am guessing you want a hashmap for character vs integer and want to add the integer to already present value in case the value is present.You can do something like below:
public hashMapImpl(char ch, int number){
Map<Character,Integer> map = new HashMap<>();
if(map.containsKey(ch)){
map.put(ch, map.get(ch)+number);
}
else{
map.put(ch,number);
}
}
Where ch will be your key and number will be something that you want to store at particular key.
you can use compute method to add/sum a value in case a key exists, or create a new entry in case it doesn't.
Map<String, Integer> map = new HashMap<>();
String myKey = "a";
Integer myValue = 10;
map.compute(myKey, (key, value) -> {
if (value == null)
return myValue;
else
return value + myValue;
}
);
System.out.println(map);
map.compute(myKey, (key, value) -> {
if (value == null)
return myValue;
else
return value + myValue;
}
);
System.out.println(map);
Outputs:
a={10}
a={20}
Of course, putting this compute logic inside a method will make you code cleaner :)
I will use an example class called HashMapExamle to explain this.
Inside the class I will create a HashMap called bigHashMap assuming that was your initial hashMap with prior data.
I also have a main method to call the method that will solve your problem. I have named the method bigHashMap. So for starters, i have initialized our prior HashMap named bigHashMap and initialized wit with some new key-value pairs.
I will printout the value of the HashMap. I will then add a value with the same key, in this case food with the value 15, by calling the hashMapValueAdd method I have created and passing the key(food) and value(15) to it.
The concept of the method is:
Check if the HashMap contains the key.
if it has it, it will get the value with that ky and add the new value to it. it will then replace the value at the key with the new value.
If the key is not found in the hashmap then the new key-value pair will just be inserted.
class HashMapExample {
private static HashMap<String, Integer> bigHashMap;
public static void main(String[] args) {
bigHashMap = new HashMap<>();
// Add test data
bigHashMap.put("food", 200);
bigHashMap.put("transport", 20);
bigHashMap.put("entertainment", 40);
System.out.println("Data before : \n" + bigHashMap);
hashmapValueAdd("food", 15);
System.out.println("Data after : \n" + bigHashMap);
}
private static void hashmapValueAdd(String key, int value) {
// Check if hashMap contains the given key
if (bigHashMap.containsKey(key)) {
// Get previous value with the same key
int valueWithSameKey = bigHashMap.get(key);
// Increment the value with incoming value
int newValue = valueWithSameKey + value;
// Put updated value into HashMap
// bigHashMap.put(key, +value);
bigHashMap.replace(key, newValue);
} else {
// Put the current key since it does not exist in the HashMap
bigHashMap.put(key, value);
}
}
}
I hope this solves your problem.
You can check out these HashMap explanations to get a better understanding.
Java HashMap - W3Schools
Java MAp - Jakob Jenkov
Java HashMap replace()
Update the Value Associated With a Key in a HashMap

Search Hashmap with Integer[] as a key [duplicate]

This question already has answers here:
How to make HashMap work with Arrays as key?
(9 answers)
Closed 3 years ago.
Let's say that I've got a Hashmap and I would like array of two Integers to actually be the key of each value. I can't figure out how to get the correct value back. It should already be stored in the Hashmap
public class Mapky {
public static void main(String[] args) {
HashMap<Integer[], String> mapka = new HashMap<>();
mapka.put(new Integer[]{10,23}, "Hello");
System.out.println(mapka.get(new Integer[]{10,23}));
}
}
Also why does this
System.out.println(new Integer[]{10,23}.equals(new Integer[]{10,23}));
return false?
You have to provide a reference to the key.
If you create a new Integer[]{10, 23}, you will create a different one which has the same value but is not the key.
Do it like this:
public static void main(String[] args) {
Map<Integer[], String> mapka = new HashMap<>();
Integer[] key = new Integer[]{10, 23};
mapka.put(key, "Hello");
System.out.println(mapka.get(key));
}

Nullpointerexception when I perform depth first search [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Suppose area1 has three contents 2,3,4, area2 has three contents 1,2,3 and area3 has two contents 1,2. m is the map that keys are locationid and values are list of contentid. For example, area1 has the map (1,{2,3,4}). Each area choose 1 content and find all the combination. I use dfs (recursion) to solve this problem but there is a nullpointerexception in line1. The intermediate is a list of string and i iterate through the list and their types are both string, why there is a null pointer exception? This is a specific condition in nullpointerexception and it is not duplicate.
public static List<String> dfs(String digits,Map<String, List<String>> m) {
List<String> result = new ArrayList<String>();
if(digits.length() == 0){
return result;
}
if(digits.length() == 1){
return m.get(digits.charAt(0));
}
List<String> intermediate = dfs(digits.substring(1, digits.length()),m);
for(String first : m.get(Character.toString(digits.charAt(0)))){
for(String rest : intermediate){ // line1
result.add(first + rest);
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String digits="123";
Map<String,List<String>> selected=new HashMap<>();
selected.put("1", new ArrayList<>(Arrays.asList("4","2","3")));
selected.put("2", new ArrayList<>(Arrays.asList("1","2","3")));
selected.put("3", new ArrayList<>(Arrays.asList("1","2")));
dfs(digits,selected);
}
I guess the problem is here:
return m.get(digits.charAt(0));
it should return null, since digits.charAt(0) is not a String
you need to use substring or Character.toString( here to extract the number

How do I update the element at a certain position in an ArrayList? [duplicate]

This question already has answers here:
Java ArrayList replace at specific index
(6 answers)
Closed 4 years ago.
I have one ArrayList of 10 Strings. How do I update the index 5 with another String value?
Let arrList be the ArrayList and newValue the new String, then just do:
arrList.set(5, newValue);
This can be found in the java api reference here.
list.set(5,"newString");
Reference
arrList.set(5,newValue);
and if u want to update it then add this line also
youradapater.NotifyDataSetChanged();
import java.util.ArrayList;
import java.util.Iterator;
public class javaClass {
public static void main(String args[]) {
ArrayList<String> alstr = new ArrayList<>();
alstr.add("irfan");
alstr.add("yogesh");
alstr.add("kapil");
alstr.add("rajoria");
for(String str : alstr) {
System.out.println(str);
}
// update value here
alstr.set(3, "Ramveer");
System.out.println("with Iterator");
Iterator<String> itr = alstr.iterator();
while (itr.hasNext()) {
Object obj = itr.next();
System.out.println(obj);
}
}}
arrayList.set(location,newValue);
location= where u wnna insert, newValue= new element you are inserting.
notify is optional, depends on conditions.

help with java hash map

can some one please explain what is happening in the code below and how it ends up with 36?
thanks
edit by Amir Rachum
public class HashMap2009 {
public static void main (String[] args) {
Map<String, Integer> myMap2009 =
new HashMap<String, Integer>();
myMap2009.put("one", new Integer(1));
myMap2009.put("three", new Integer(3));
myMap2009.put("five", new Integer(5));
myMap2009.put("seven", new Integer(7));
myMap2009.put("nine", new Integer(9));
System.out.println(oddOne(myMap2009));
}
private static int oddOne(Map<String, Integer> myMap2009) {
if (myMap2009.isEmpty())
return 11;
else {
Set<String> st = myMap2009.keySet();
String key = st.iterator().next();
int num = myMap2009.get(key);
myMap2009.remove(key);
return num + oddOne(myMap2009);
}
}
}
This is a simple example of recursion, which results in adding up all the keys in the map one by one and when the map is empty, it adds another 11. This sums up to 36.
That's a recursive function, that each time it is called, add the value of the first element in the map and then remove it.
If the map is empty it return 11
So: 9+7+5+3+1+11 = 36 ( 9,7,5,3,1 for each value in the map and 11 for when it is empty )
BTW, this looks to me as a terrible way to teach recursion ( because the map creates too much noise )
A simpler ( and I think more effective ) way would've been:
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
public class ArrayList2009 {
public static void main( String [] args ) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(5);
list.add(7);
list.add(9);
System.out.println( addOne( list ) );
}
private static int addOne( List<Integer> list ){
if ( list.isEmpty() ) {
return 11;
} else {
Iterator<Integer> i = list.iterator();
int num = i.next();
i.remove();
return num + addOne( list );
}
}
}
Which does exactly the same, but introduce less noise because the List interface easier to understand.
When calling oddOne it will get
the first number
remove the number
add it to the result of oddOne (with the number removed)
this repeats till empty whne oddOne return 11
so we end up with
1 + (3 + (5 + (7 + (9 + 11)))) = 36
actually the order will e all jumbled up as it is a hashmap but this has no influence on adding numbers
You're making recursive calls, removing one element from the map per call.
You could start out with num == 1 (a map is unordered) and you remove this from your map. Then you do the recursive call, which gives you num == 3. This continues until your map is empty, which results in 1 + 3 + 5 + 7 + 9, and an additional 11 for your empty map.
Take a look at recursion: http://en.wikipedia.org/wiki/Recursion

Categories