How to SUM duplicate key values in LinkedHashMap? - java

I have a LinkedHashMap where I have two duplicate keys with their correspondent values, I need to know how to SUM those values into one key. Currently he eliminates the old duplicated value and put the new one
This is my Map
static Map<String, Double> costByDuration = new LinkedHashMap<>();
This is where I put the values ( call_from can be 912345678 and have a value of 10, and then another call from 912345678 and have a value of 20), then I want 912345678 to have a value of 30 instead of keeping only one.
costByDuration.put(call_from, toPay);

I'd create a method as follows:
public void put(String key, Double value){
costByDuration.merge(key,value , Double::sum);
}
then the use case would be:
put(call_from, toPay);
put(anotherKey, anotherValue);
...
...
This solution internally uses the merge method which basically says if the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function.

You'll have to check first whether your value is already in the map.
Double existingValue = costByDuration.get(callFrom);
if (existingValue != null) {
costByDuration.put(callFrom, existingValue + toPay);
} else {
costByDuration.put(callFrom, toPay);
}
Incidentally, it's a bad idea to use a Double to store an amount of money, if you want your arithmetic operations to give you the correct answer. I strongly recommend using BigDecimal in place of Double.

Use merge function:
costByDuration.merge(call_from, toPay, (oldPay, toPay) -> oldPay + toPay);

Try this using containsKey method :
static Map<String, Double> costByDuration = new LinkedHashMap<>();
if(costByDuration.containsKey(call_from) {
costByDuration.put(call_from, map.get(call_from) + to_Pay);
} else {
costByDuration.put(call_from, to_Pay);
}

Related

Java8: About order of Map elements returned by Collectors.groupingBy

would like to seek for advice on the following piece of code modified from an example came across.
I was wondering whether the output sequence in the resulting Map would change when the input List element sequence is changed. However, it seems the output is the same in all cases (I have run the program repeatedly on IDE). May I seek for advice on whether the order of the resulting Map elements can be expected?
Will there be any difference in sequence (alphabetical/non-alphbetical?) when using enum or String, or the element sequence is simply random?
public class TestCountry {
public enum Continent {ASIA, EUROPE}
String name;
Continent region;
public TestCountry (String na, Continent reg) {
name = na;
region = reg;
}
public String getName () {
return name;
}
public Continent getRegion () {
return region;
}
public static void main(String[] args) {
List<TestCountry> couList1 = Arrays.asList (
new TestCountry ("Japan", TestCountry.Continent.ASIA),
new TestCountry ("Italy", TestCountry.Continent.EUROPE),
new TestCountry ("Germany", TestCountry.Continent.EUROPE));
List<TestCountry> couList2 = Arrays.asList (
new TestCountry ("Italy", TestCountry.Continent.EUROPE),
new TestCountry ("Japan", TestCountry.Continent.ASIA),
new TestCountry ("Germany", TestCountry.Continent.EUROPE));
Map<TestCountry.Continent, List<String>> mapWithRegionAsKey1 = couList1.stream ()
.collect(Collectors.groupingBy (TestCountry ::getRegion,
Collectors.mapping(TestCountry::getName, Collectors.toList())));
Map<String, List<Continent>> mapWithNameAsKey1 = couList1.stream ()
.collect(Collectors.groupingBy (TestCountry::getName,
Collectors.mapping(TestCountry::getRegion, Collectors.toList())));
Map<TestCountry.Continent, List<String>> mapWithRegionAsKey2 = couList2.stream ()
.collect(Collectors.groupingBy (TestCountry ::getRegion,
Collectors.mapping(TestCountry::getName, Collectors.toList())));
Map<String, List<Continent>> mapWithNameAsKey2 = couList2.stream ()
.collect(Collectors.groupingBy (TestCountry::getName,
Collectors.mapping(TestCountry::getRegion, Collectors.toList())));
System.out.println("Value of mapWithRegionAsKey1 in couList1: " + mapWithRegionAsKey1);
System.out.println("Value of mapWithNameAsKey1 in couList1: " + mapWithNameAsKey1);
System.out.println("Value of mapWithRegionAsKey2 in couList2: " + mapWithRegionAsKey2);
System.out.println("Value of mapWithNameAsKey2 in couList2: " + mapWithNameAsKey2);
}
}
/*
* Output:
Value of mapWithRegionAsKey1 in couList1: {ASIA=[Japan], EUROPE=[Italy,
Germany]}
Value of mapWithNameAsKey1 in couList1: {Japan=[ASIA], Italy=[EUROPE],
Germany=[EUROPE]}
Value of mapWithRegionAsKey2 in couList2: {ASIA=[Japan], EUROPE=[Italy,
Germany]}
Value of mapWithNameAsKey2 in couList2: {Japan=[ASIA], Italy=[EUROPE],
Germany=[EUROPE]}
*/
Collectors.groupingBy() currently returns a HashMap. This is an implementation detail that can change in future versions.
The entries of a HashMap are not sorted, but the order in which they are iterated (when printing the HashMap) is deterministic, and doesn't depend on insertion order.
Therefore you see the same output, regardless of the order of the elements in the input List. You shouldn't rely on that order, though, since it's an implementation detail.
If you care about the order of the entries in the output Map, you can modify the code to produce a LinkedHashMap (where the default order is insertion order) or a TreeMap (where the keys are sorted).
BTW, if you change your input to
List<TestCountry> couList1 = Arrays.asList (
new TestCountry ("Japan", TestCountry.Continent.ASIA),
new TestCountry ("Italy", TestCountry.Continent.EUROPE),
new TestCountry ("Germany", TestCountry.Continent.EUROPE));
List<TestCountry> couList2 = Arrays.asList (
new TestCountry ("Germany", TestCountry.Continent.EUROPE),
new TestCountry ("Italy", TestCountry.Continent.EUROPE),
new TestCountry ("Japan", TestCountry.Continent.ASIA)
);
you will get a different order in the output:
Value of mapWithRegionAsKey1 in couList1: {ASIA=[Japan], EUROPE=[Italy, Germany]}
Value of mapWithNameAsKey1 in couList1: {Japan=[ASIA], Italy=[EUROPE], Germany=[EUROPE]}
Value of mapWithRegionAsKey2 in couList2: {ASIA=[Japan], EUROPE=[Germany, Italy]}
Value of mapWithNameAsKey2 in couList2: {Japan=[ASIA], Italy=[EUROPE], Germany=[EUROPE]}
This results from the fact that the elements of the individual output Lists (which are ArrayLists in the current implementation) are ordered according to insertion order, which depends on the ordering of your input List.
Before questioning this, read the documentation which says:
There are no guarantees on the type, mutability, serializability, or thread-safety of the Map or List objects returned.
So if you can't tell what type of the Map is returned, you can't really tell what order (if any) there will be. Well at the moment, As Eran points out it is a HashMap, but that is not guaranteed.
The question is why would you care abut this? If it for academic purposes, it makes sense, if not, collect to something that does guarantee the order.
Collectors.groupingBy take a parameter that allows you to specify the actual Map implementation you might need.

Add number in map java

I am creating a function that loops through a string, separates it by comma and then takes the key from the second item in the array and the value from the 1st after splitting the string.
I then want to place these values in a map. This works perfectly, however if i have two strings with the same key it doesn't add the value up it just replaces it.
For example if my string was
123,totti 100,roma, 100,totti
I would want
totti 223
roma 100
Here is my code
private void processCallLogs(String[] splitCalls) {
for (String individualCall : splitCalls) {
int duration = 0;
String[] singleCall = individualCall.split(",");
duration += DurationParser.returnDuration(singleCall[0]);
this.cost += CalculateCost.calculateCostPerCall(singleDuration);
if (totalCallDurations.containsKey(singleCall[1])) {
totalCallDurations.put(singleCall[1], singleDuration);
} else {
totalCallDurations.put(singleCall[1], duration);
}
}
}
You can replace the if with something like this:
if (totalCallDurations.containsKey(singleCall[1])) {
duration += totalCallDurations.get(singleCall[1]);
}
totalCallDurations.put(singleCall[1], duration);
Create a map and update the value if the key is present
public static void main(String[] args) {
myMap = new HashMap<>();
// 123,totti 100,roma, 100,totti
addToMap("totti", 123);
addToMap("roma", 100);
addToMap("totti", 100);
System.out.println(myMap);
}
private static void addToMap(String string, int i) {
int t = i;
if (myMap.get(string) != null) {
t += myMap.get(string);
}
myMap.put(string, t);
}
If you're using Java 8, you can do this easily with the Map.merge() method:
totalCallDurations.merge(singleCall[1], duration, Integer::sum);
If you want to make a map that will add the values together instead of replacing, I would recommend extending the Map type to make your own map. Since Map is very abstract. I would extend HashMap. (I suggest this both for code style and because it will make your code more extendable).
public class AdderMap extends HashMap<String, Integer> { // This extends the HashMap class
public Integer get(String key) { // This overrides the Map::get method
if(super.containsKey(key)) return super.get(key); // If the key-value pairing exists, return the value
else return 0; // If it doesn't exist, return 0
}
public Integer put(String key, Integer value) { // This overrides the Map::put method
Integer old_value = this.get(key); // Get the former value of the key-value pairing (which is 0 if it doesn't exist)
super.put(key, old_value + value); // Add the new value to the former value and replace the key-value pairing (this behaves normally when the former value didn't exist)
return old_value; // As per the documentation, Map::put will return the old value of the key-value pairing
}
}
Now, when you initialize your map, make it an AdderMap. Then, you can just use put(String, Integer) and it will add it together.
The advantage of this solution is that it helps with keeping your code clean and it allows you to use this type of map again in the future without needing separate code in your main code. The disadvantage is that it requires another class, and having too many classes can become cluttered.

Arraylist - String/Double

I am taking a basic objects first with java class, i don't know much yet and need a little help ..
I need to assign these values to an arraylist but also need to allow the user to choose a health option based on a string that will then output the value related to the option..
double [] healthBenDesig = new double [5];
double [] healthBenDesig = {0.00, 311.87, 592.56, 717.30, 882.60};
Strings I want to assign are:
none = 0.00
employeeOnly = 311.87
spouse = 592.56
children = 717.30
kids = 882.60
Ultimately, I want the user to input for example "none" and the output will relate none to the value held in the arraylist [0] slot and return that value. Is this possible? Or is there an easier way I am overlooking?
if anyone could help me out I would really appreciate it :)
Thanks
Yes. This is possible with HashMap.
HashMap<String,Double> healthMap = new HashMap<String,Double>();
healthMap.put("none",0.00);
healthMap.put("employeeOnly",311.87);
healthMap.put("spouse",592.56);
healthMap.put("children",717.30);
healthMap.put("kids",882.60);
Now, when user enters none then use get() method on healthMap to get the value.
For safety check that key exists in map using containsKey() method.
if(healthMap.containsKey("none")) {
Double healthVal = healthMap.get("none"); //it will return Double value
} else {
//show you have entered wrong input
}
See also
HashMap oracle docs
Best solution is Map<String, Double>.
Map<String,Double> map=new HashMap<>();
map.put("none",0.0);
Now when you want the value for "none" you can use get() method
map.get("none") // will return 0.0
Here's something for you to get started with since it's the assignment:
Create a Map<String, Double> that holds the number and string as key/value pair.
Store the above values into the map
When a user enters the input, capture it using Scanner
Do something like this.
if(map.containsKey(input)) {
value = map.get(input);
}
Use Map Inteface
Map<String, Double> healthBenDesig =new HashMap<String, Double>();
healthBenDesig.put("none", 0.00);
healthBenDesig.put("employeeOnly", 311.87);
healthBenDesig.put("spouse", 592.56);
healthBenDesig.put("children", 717.30);
healthBenDesig.put("kids", 882.60);
System.out.println(healthBenDesig);
OutPut
{
none = 0.0,
spouse = 592.56,
children = 717.3,
kids = 882.6,
employeeOnly = 311.87
}

Changing LinkedHashMapValues

Below is data from 2 linkedHashMaps:
valueMap: { y=9.0, c=2.0, m=3.0, x=2.0}
formulaMap: { y=null, ==null, m=null, *=null, x=null, +=null, c=null, -=null, (=null, )=null, /=null}
What I want to do is input the the values from the first map into the corresponding positions in the second map. Both maps take String,Double as parameters.
Here is my attempt so far:
for(Map.Entry<String,Double> entryNumber: valueMap.entrySet()){
double doubleOfValueMap = entryNumber.getValue();
for(String StringFromValueMap: strArray){
for(Map.Entry<String,Double> entryFormula: formulaMap.entrySet()){
String StringFromFormulaMap = entryFormula.toString();
if(StringFromFormulaMap.contains(StringFromValueMap)){
entryFormula.setValue(doubleOfValueMap);
}
}
}
}
The problem with doing this is that it will set all of the values i.e. y,m,x,c to the value of the last double. Iterating through the values won't work either as the values are normally in a different order those in the formulaMap. Ideally what I need is to say is if the string in formulaMap is the same as the string in valueMap, set the value in formulaMap to the same value as in valueMap.
Let me know if you have any ideas as to what I can do?
This is quite simple:
formulaMap.putAll(valueMap);
If your value map contains key which are not contained in formulaMap, and you don't want to alter the original, do:
final Map<String, Double> map = new LinkedHashMap<String, Double>(valueMap);
map.keySet().retainAll(formulaMap.keySet());
formulaMap.putAll(map);
Edit due to comment It appears the problem was not at all what I thought, so here goes:
// The result map
for (final String key: formulaMap.keySet()) {
map.put(formulaMap.get(key), valueMap.get(key));
// Either return the new map, or do:
valueMap.clear();
valueMap.putAll(map);
for(Map.Entry<String,Double> valueFormula: valueMap.entrySet()){
formulaMap.put(valueFormula.getKey(), valueFormula.value());
}

Get key from a HashMap using the value [duplicate]

This question already has answers here:
Java Hashmap: How to get key from value?
(39 answers)
Closed 5 years ago.
I want to get the key of a HashMap using the value.
hashmap = new HashMap<String, Object>();
haspmap.put("one", 100);
haspmap.put("two", 200);
Which means i want a function that will take the value 100 and will return the string one.
It seems that there are a lot of questions here asking the same thing but they don't work for me.
Maybe because i am new with java.
How to do it?
The put method in HashMap is defined like this:
Object put(Object key, Object value)
key is the first parameter, so in your put, "one" is the key. You can't easily look up by value in a HashMap, if you really want to do that, it would be a linear search done by calling entrySet(), like this:
for (Map.Entry<Object, Object> e : hashmap.entrySet()) {
Object key = e.getKey();
Object value = e.getValue();
}
However, that's O(n) and kind of defeats the purpose of using a HashMap unless you only need to do it rarely. If you really want to be able to look up by key or value frequently, core Java doesn't have anything for you, but something like BiMap from the Google Collections is what you want.
We can get KEY from VALUE. Below is a sample code_
public class Main {
public static void main(String[] args) {
Map map = new HashMap();
map.put("key_1","one");
map.put("key_2","two");
map.put("key_3","three");
map.put("key_4","four");
System.out.println(getKeyFromValue(map,"four"));
}
public static Object getKeyFromValue(Map hm, Object value) {
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
return o;
}
}
return null;
}
}
I hope this will help everyone.
If you need only that, simply use put(100, "one"). Note that the key is the first argument, and the value is the 2nd.
If you need to be able to get by both the key and the value, use BiMap (from guava)
You have it reversed. The 100 should be the first parameter (it's the key) and the "one" should be the second parameter (it's the value).
Read the javadoc for HashMap and that might help you: HashMap
To get the value, use hashmap.get(100).
You mixed the keys and the values.
Hashmap <Integer,String> hashmap = new HashMap<Integer, String>();
hashmap.put(100, "one");
hashmap.put(200, "two");
Afterwards a
hashmap.get(100);
will give you "one"
if you what to obtain "ONE" by giving in 100 then
initialize hash map by
hashmap = new HashMap<Object,String>();
haspmap.put(100,"one");
and retrieve value by
hashMap.get(100)
hope that helps.
public class Class1 {
private String extref="MY";
public String getExtref() {
return extref;
}
public String setExtref(String extref) {
return this.extref = extref;
}
public static void main(String[] args) {
Class1 obj=new Class1();
String value=obj.setExtref("AFF");
int returnedValue=getMethod(value);
System.out.println(returnedValue);
}
/**
* #param value
* #return
*/
private static int getMethod(String value) {
HashMap<Integer, String> hashmap1 = new HashMap<Integer, String>();
hashmap1.put(1,"MY");
hashmap1.put(2,"AFF");
if (hashmap1.containsValue(value))
{
for (Map.Entry<Integer,String> e : hashmap1.entrySet()) {
Integer key = e.getKey();
Object value2 = e.getValue();
if ((value2.toString()).equalsIgnoreCase(value))
{
return key;
}
}
}
return 0;
}
}
If you are not bound to use Hashmap, I would advise to use pair< T,T >.
The individual elements can be accessed by first and second calls.
Have a look at this http://www.cplusplus.com/reference/utility/pair/
I used it here : http://codeforces.com/contest/507/submission/9531943

Categories

Resources