What's the best way to sum two Map<String,String>? - java

I have the following maps.
Map<String,String> map1= new HashMap<String, String>(){{
put("no1","123"); put("no2","5434"); put("no5","234");}};
Map<String,String> map1 = new HashMap<String, String>(){{
put("no1","523"); put("no2","234"); put("no3","234");}};
sum(map1, map2);
I want to join them to one, summing up similar keyed values together. What;s the best way I could do it using java 7 or guava libraries ?
expected output
Map<String, String> output = { { "no1" ,"646"}, { "no2", "5668"}, {"no5","234"}, {"no3","234" } }

private static Map<String, String> sum(Map<String, String> map1, Map<String, String> map2) {
Map<String, String> result = new HashMap<String, String>();
result.putAll(map1);
for (String key : map2.keySet()) {
String value = result.get(key);
if (value != null) {
Integer newValue = Integer.valueOf(value) + Integer.valueOf(map2.get(key));
result.put(key, newValue.toString());
} else {
result.put(key, map2.get(key));
}
}
return result;
}

try this
Map<String, List<String>> map3 = new HashMap<String, List<String>>();
for (Entry<String, String> e : map1.entrySet()) {
List<String> list = new ArrayList<String>();
list.add(e.getValue());
String v2 = map2.remove(e.getKey());
if (v2 != null) {
list.add(v2);
}
map3.put(e.getKey(), list);
}
for (Entry<String, String> e : map2.entrySet()) {
map3.put(e.getKey(), new ArrayList<String>(Arrays.asList(e.getValue())));
}

Java 8 introduces Map.merge(K, V, BiFunction), which makes this easy if not particularly concise:
Map<String, String> result = new HashMap<>(map1);
//or just merge into map1 if mutating it is okay
map2.forEach((k, v) -> result.merge(k, v, (a, b) ->
Integer.toString(Integer.parseInt(a) + Integer.parseInt(b))));
If you're doing this repeatedly, you're going to be parsing and creating a lot of strings. If you're generating the maps one at a time, you're best off maintaining a list of strings and only parsing and summing once.
Map<String, List<String>> deferredSum = new HashMap<>();
//for each map
mapN.forEach((k, v) ->
deferredSum.computeIfAbsent(k, x -> new ArrayList<String>()).add(v));
//when you're done
Map<String, String> result = new HashMap<>();
deferredSum.forEach((k, v) -> result.put(k,
Long.toString(v.stream().mapToInt(Integer::parseInt).sum())));
If this summing is a common operation, consider whether using Integer as your value type makes more sense; you can use Integer::sum as the merge function in that case, and maintaining lists of deferred sums would no longer be necessary.

Try this
Map<String,String> map1= new HashMap<String, String>(){{
put("no1","123"); put("no2","5434"); put("no5","234");}};
Map<String,String> map2 = new HashMap<String, String>(){{
put("no1","523"); put("no2","234"); put("no3","234");}};
Map<String,String> newMap=map1;
for(String a:map2.keySet()){
if(newMap.keySet().contains(a)){
newMap.put(a,""+(Integer.parseInt(newMap.get(a))+Integer.parseInt(map2.get(a))));
}
else{
newMap.put(a,map2.get(a));
}
}
for(String k : newMap.keySet()){
System.out.println("key : "+ k + " value : " + newMap.get(k));
}

Related

Streams for iterating through Map of List of Map in Java

I have a map that contains Integer as key and (List of Map of String as key and boolean as the value) as value. Map<Int, List<Map<String, Boolean>>>, I want to populate a set that has Int as key of the outer map based on condition.
MyService.java
public Set<Integer> getValue(String input){
Map<String, Boolean> in1 = new HashMap<>();
in1.put("test_1", true);
Map<String, Boolean> in2 = new HashMap<>();
in2.put("test_2", false);
Map<String, Boolean> in3 = new HashMap<>();
in2.put("test_3", false);
Map<String, Boolean> in4 = new HashMap<>();
in2.put("test_4", true);
List<Map<String, Boolean>> l1 = new ArrayList<>();
l1.add(in1);
l1.add(in2);
List<Map<String, Boolean>> l2 = new ArrayList<>();
l2.add(in3);
l2.add(in4);
Map<Integer, List<Map<String,Boolean>>> map = new HashMap();
map.put(123, l1);
map.put(345, l2);
Set<Integer> result = new HashSet<>();
for(Map.Entry<Integer, List<Map<String, Boolean>>> entry : map.entrySet()){
for(Map<String, Boolean> m: entry.getValue() ){
if(m.containsKey(input) && m.get(input) == true){
result.add(entry.getKey());
}
}
}
return result;
}
So, basically I want to iterate from first the exterior map to get the internal map and then iterate the internal map to check if the input is present and add it to a set. How can I do this using java 8 streams?
I tried with for loop, but I will like to replace it using Java streams.
This produced the same results as your code in a test that passed "test_1", etc. into it.
map.entrySet().stream()
.filter(entry -> entry.getValue().stream()
.anyMatch(m -> m.getOrDefault(input, false)))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());

Hashmap. Find key(s) which have same values between two hashmaps

Lets consider we have two hashmaps as below:
HashMap<String, Integer> map1 = new HashMap<>();
map1.put("vishal", 10);
map1.put("sachin", 30);
map1.put("vaibhav", 20);
HashMap<String, Integer> map2 = new HashMap<>();
map2.put("Raja", 10);
map2.put("John", 30);
map2.put("Krishna", 20);
The "vaibhav" from map1 and "krishna" from map2 have the same values.
I need to find the keys from both the maps, which have the same values. In this case, "vaibhav" and "Krishna".
Thanks.
Group by values and store keys in list:
Stream.of(map1.entrySet(), map2.entrySet())
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(
Map.Entry::getValue,
Collectors.mapping(
Map.Entry::getKey,
Collectors.toList()
)
));
It will create:
{20=[vaibhav, Krishna], 10=[vishal, Raja], 30=[sachin, John]}
UPDATE
Other approach
Map<Integer, List<String>> collect = new HashMap<>();
map1.entrySet().forEach(e -> collect
.computeIfAbsent(e.getValue(), k -> new ArrayList<>())
.add(e.getKey()));
map2.entrySet().forEach(e -> collect
.computeIfAbsent(e.getValue(), k -> new ArrayList<>())
.add(e.getKey()));
You can improve the time complexity to O(n + m) where n is the size of first map and m is the size of the second map.
We can achieve this by making values as keys and keys as values.
Steps:
Iterate over each map.
Store all current map values in a new map and collect all keys who have that value in a list and put the current value with this list in the new map.
Now, iterate over any of the new map collections and get the common keys and it's respective values for printing.
Snippet:
private static void showCommonValueKeys(HashMap<String, Integer> map1,HashMap<String, Integer> map2){
Map<Integer,List<String>> map1Collect = flipKeyValue(map1);
Map<Integer,List<String>> map2Collect = flipKeyValue(map2);
for(Map.Entry<Integer,List<String>> m : map1Collect.entrySet()){
int key = m.getKey();
if(map2Collect.containsKey(key)){
System.out.println("For value " + key);
System.out.println("First map keys: " + m.getValue().toString());
System.out.println("Second map keys: " + map2Collect.get(key).toString());
System.out.println();
}
}
}
private static Map<Integer,List<String>> flipKeyValue(HashMap<String, Integer> map){
Map<Integer,List<String>> mapCollect = new HashMap<>();
for(Map.Entry<String,Integer> m : map.entrySet()){
String key = m.getKey();
int val = m.getValue();
mapCollect.putIfAbsent(val,new ArrayList<>());
mapCollect.get(val).add(key);
}
return mapCollect;
}
Demo: https://onlinegdb.com/SJdcpbOXU
This can be achieved through two for loops with a complexity of n*m, where n.m is the size of each map.
Map<String, String> map1 = new HashMap<>();
map1.put("santhosh", "1");
map1.put("raja", "2");
map1.put("arun", "3");
Map<String, String> map2 = new HashMap<>();
map2.put("kumar", "1");
map2.put("mani", "1");
map2.put("tony", "3");
for (Map.Entry<String, String> entry1 : map1.entrySet()) {
String key1 = entry1.getKey();
String value1 = entry1.getValue();
for (Map.Entry<String, String> entry2 : map2.entrySet()) {
String key2 = entry2.getKey();
String value2 = entry2.getValue();
if (value1 == value2) {
System.out.println(key1 + " " + key2);
}
}
Thanks.

update existing key of HashMap

I have HashMap < Integer,String> of length 3:
1=>"Value1"
2=>"Value2"
3=>"Value3"
Now I want to decrease all keys by 1(if key>1):
Output:
1=>"Value2"
2=>"Value3"
What I am trying
for (e in hashMap.entries) {
val entry = e as Map.Entry<*, *>
var keyPos = (entry.key as Int)
if (keyPos != -1) {
if (keyPos > 1) {
keyPos = keyPos - 1
if (keyPos != -1) {
hashMap.put(keyPos, entry.value as String?)
}
}
}
}
But its not giving required output.
How to make it work without Concurrency exception.
An alternative is to use mapKeys extension function, which allows you to redefine the key for a map entry:
fun main() {
val originalMap = mapOf(1 to "value1", 2 to "value2", 3 to "value3")
val updatedMap = originalMap
.mapKeys {
if (it.key > 1) {
it.key - 1
} else {
it.key
}
}
println(updatedMap) // prints: {1=value2, 2=value3}
}
Note that this will not update the map in-place, but it will create a new one. Also note that:
In case if any two entries are mapped to the equal keys, the value of the latter one will overwrite the value associated with the former one.
This means that in case two keys are conflicting, in general you can't know which one will "win" (unless you're using a LinkedHashMap, which preserves insertion order).
A more general approach would be to:
decrement all keys
filter out all non-positive keys
This will require 2 full iterations, though, (unless you use Sequences, which are lazily evaluated):
fun main() {
val originalMap = mapOf(1 to "value1", 2 to "value2", 3 to "value3")
val updatedMap = originalMap
.mapKeys {
it.key - 1
}.filter {
it.key > 0
}
println(updatedMap)
}
EDIT: here is the same with Java 7 compatible code (without streams)
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "test1");
hashMap.put(2, "test2");
hashMap.put(3, "test3");
Map<Integer, String> yourNewHashMap = new HashMap<>();
for (final Map.Entry<Integer, String> entry : hashMap.entrySet()) {
if (entry.getKey() != 1) { // make sure index 1 is omitted
yourNewHashMap.put(entry.getKey() - 1, entry.getValue()); // decrease the index for each key/value pair and add it to the new map
}
}
Old answer with streams:
As a new Map Object is okay for you, I would go with the following stream:
comments are inline
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "test1");
hashMap.put(2, "test2");
hashMap.put(3, "test3");
// use this
Map<Integer, String> yourNewHashMap = hashMap.entrySet().stream()
.filter(es -> es.getKey() != 1) // make sure index 1 is omitted
.map(es -> new AbstractMap.SimpleEntry<Integer, String>(es.getKey() - 1, es.getValue())) // decrease the index for each key/value pair
.collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); // create a new map
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
// Populate the HashMap
map.put(1, "Value1");
map.put(2, "Value2");
map.put(3, "Value3");
System.out.println("Original HashMap: "
+ map);
decreaseAllKeysByOne(map);
}
private static void decreaseAllKeysByOne(HashMap<Integer, String> map) {
// Add your condition (if key>1)
HashMap<Integer, String> newMap = new HashMap<>();
map.remove(1);
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
int i = 1;
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
newMap.put(i, entry.getValue());
i++;
}
System.out.println("Modified HashMap: "
+ newMap);
}
Output :
Original HashMap: {1=Value1, 2=Value2, 3=Value3}
Modified HashMap: {1=Value2, 2=Value3}

Get Map key and value from two different Map with key and vlue in java

There are two Map, first one contains student id and name. second one contains student id and status of 'Pass' or 'Fail'. There is a method which takes two parameters of Map type and returns Map.
//1st Map
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, "x");
map1.put(2, "y");
map1.put(3, "z");
map1.put(4, "a");
map1.put(5, "b");`
and
//2nd Map
Map<Integer, String> map2 = new HashMap<>();
map2.put(1, "fail");
map2.put(2, "fail");
map2.put(3, "fail");
map2.put(4, "pass");
map2.put(5, "pass");`
//the method
public Map<Integer, String>findFaildStudent(Map<Integer, String>map1,Map<Integer, String>map2){
returns Map<Integer, String>;
}
So, my question is how to find the record of failed students. I did try it myself but didn't succeed. Any help is appreciated.
What I tried so far
public Map<Integer, String>findFaildStudent(Map<Integer, String>map1,Map<Integer, String>map2){
Integer key = null;
String value = null;
Iterator<Entry<Integer, String>> iterator = map1.entrySet().iterator();
while(iterator.hasNext()){
Entry<Integer, String> next = iterator.next();
key = next.getKey();
}
Iterator<Entry<Integer, String>> iterator2 = map2.entrySet().iterator();
while(iterator2.hasNext()){
Entry<Integer, String> next = iterator2.next();
value=next.getValue();
}
Map<Integer,String> hashMap = new HashMap<>();
hashMap.put(key, value);
return hashMap;
}
public Map<String, String> findFaildStudent(Map<Integer, String>map1,Map<Integer, String>map2){
Map<String, String> failed = new HashMap<>();
for (Map.Entry<Integer, String> k : map2.entrySet()) {
if(k.getValue().equals("fail")){
failed.put(map1.get(k.getKey()), map2.get(k.getValue()));
}
}
return failed;
}
//returns... ("x","failed"), ("y", "failed"), ("z", "failed")
So basically you just need to iterate through the 2nd map since it contain failed student, then you get the key and use that key to get the value of map1.
You cannot concate the keys because the key is unique so if you want combine both map together it is better to create another map using map1(value) as key and map2(value) as value. Hope I understand your question but if you only want map2 of failed student then try below.
public Map<Integer, String> findFaildStudent(Map<Integer, String>map1,Map<Integer, String>map2){
Map<Integer, String> failed = new HashMap<>();
for (Map.Entry<Integer, String> k : map2.entrySet()) {
if(k.getValue().equals("fail")){
failed.put(k.getKey(), map1.get(k.getKey()));
}
}
return failed;
//returns... (1,"x"), (2, "y"), (3, "z")
map1.entrySet().stream()
.filter(entry -> "fail".equals(map2.get(entry.getKey())))
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));

how to merge more than one hashmaps also sum the values of same key in java

ı am trying to merge more than one hashmaps also sum the values of same key,
ı want to explain my problem with toy example as follows
HashMap<String, Integer> m = new HashMap<>();
HashMap<String, Integer> m2 = new HashMap<>();
m.put("apple", 2);
m.put("pear", 3);
m2.put("apple", 9);
m2.put("banana", 6);
ı tried putall
m.putAll(m2);
output is as follows
{banana=6, apple=9, pear=3}
but its result is not true for this problem.
ı want to output as
{banana=6, apple=11, pear=3}
how can ı get this result in java?
If you are using Java 8, you can use the new merge method of Map.
m2.forEach((k, v) -> m.merge(k, v, (v1, v2) -> v1 + v2));
This is a very nice use case for Java 8 streams. You can concatentate the streams of entries and then collect them in a new map:
Map<String, Integer> combinedMap = Stream.concat(m1.entrySet().stream(), m2.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.summingInt(Map.Entry::getValue)));
There are lots of nice things about this solution, including being able to make it parallel, expanding to as many maps as you want and being able to trivial filter the maps if required. It also does not require the orginal maps to be mutable.
This method should do it (in Java 5+)
public static <K> Map<K, Integer> mergeAndAdd(Map<K, Integer>... maps) {
Map<K, Integer> result = new HashMap<>();
for (Map<K, Integer> map : maps) {
for (Map.Entry<K, Integer> entry : map.entrySet()) {
K key = entry.getKey();
Integer current = result.get(key);
result.put(key, current == null ? entry.getValue() : entry.getValue() + current);
}
}
return result;
}
Here's my quick and dirty implementation:
import java.util.HashMap;
import java.util.Map;
public class MapMerger {
public static void main(String[] args) {
HashMap<String, Integer> m = new HashMap<>();
HashMap<String, Integer> m2 = new HashMap<>();
m.put("apple", 2);
m.put("pear", 3);
m2.put("apple", 9);
m2.put("banana", 6);
final Map<String, Integer> result = (new MapMerger()).mergeSumOfMaps(m, m2);
System.out.println(result);
}
public Map<String, Integer> mergeSumOfMaps(Map<String, Integer>... maps) {
final Map<String, Integer> resultMap = new HashMap<>();
for (final Map<String, Integer> map : maps) {
for (final String key : map.keySet()) {
final int value;
if (resultMap.containsKey(key)) {
final int existingValue = resultMap.get(key);
value = map.get(key) + existingValue;
}
else {
value = map.get(key);
}
resultMap.put(key, value);
}
}
return resultMap;
}
}
Output:
{banana=6, apple=11, pear=3}
There are some things you should do (like null checking), and I'm not sure if it's the fastest. Also, this is specific to integers. I attempted to make one using generics of the Number class, but you'd need this method for each type (byte, int, short, longer, etc)
ı improve Lucas Ross's code. in stead of enter map by one by in function ı give all maps one times to function with arraylist of hashmap like that
public HashMap<String, Integer> mergeAndAdd(ArrayList<HashMap<String, Integer>> maplist) {
HashMap<String, Integer> result = new HashMap<>();
for (HashMap<String, Integer> map : maplist) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer current = result.get(key);
result.put(key, current == null ? entry.getValue() : entry.getValue() + current);
}
}
return result;
}
}
it works too. thanks to everbody
Assume that you have many HashMaps: Map<String,Integer> map1, map2, map3;
Then you can use Java 8 streams:
Map<String,Integer> combinedMap = Stream.of(map1, map2, map3)
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.summingInt(Map.Entry::getValue)));
If the key exists, add to it's value. If not insert.
Here is a simple example which merges one map into another:
Foo oldVal = map.get(key);
if oldVal == null
{
map2.put(key, newVal);
}
else
{
map2.put(key, newVal + oldVal);
}
Obviously you have to loop over the first map so you can process all of it's entries but that's trivial.
Something like this should work:
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String map1_key = entry.getKey();
int map1_value = entry.getValue();
//check:
if(map2.get(map1_key)!=null){
int map2_value = map2.get(map1_key);
//merge:
map3.put(map1_key,map1_value+map2_value);
}else{
map3.put(map1_key,map1_value);
}
}
for (Map.Entry<String, Integer> entry2 : map2.entrySet()) {
String map2_key = entry2.getKey();
int map2_value = entry2.getValue();
//check:
if(map1.get(map2_key)!=null){
int map1_value = map1.get(map2_key);
//merge:
map3.put(map2_key,map1_value+map2_value);
}else{
map3.put(map2_key,map2_value);
}
}

Categories

Resources