How to combine 2 maps into a third map in Java

3 Answers

0 votes
import java.util.HashMap;
import java.util.Map;

class Main {
    public static void main(String[] args) {
        Map<String, String> map1 = Map.of("a", "aaa", "b", "bbb");
        Map<String, String> map2 = Map.of("b", "XYZ", "c", "ccc");

        Map<String, String> combined = new HashMap<>();
        combined.putAll(map1);
        combined.putAll(map2); 
        
        System.out.println(combined);
    }
}



/*
run:
 
{a=aaa, b=XYZ, c=ccc}
 
*/

 



answered Aug 24, 2025 by avibootz
0 votes
import java.util.HashMap;
import java.util.Map;

class Main {
    public static void main(String[] args) {
        Map<String, String> map1 = Map.of("a", "aaa", "b", "bbb");
        Map<String, String> map2 = Map.of("b", "XYZ", "c", "ccc");

        Map<String, String> combined = new HashMap<>(map1);
        map2.forEach((key, value) ->
            combined.merge(key, value, (v1, v2) -> v1 + "," + v2)
        );
        
        System.out.println(combined);
    }
}



/*
run:
 
{a=aaa, b=bbb,XYZ, c=ccc}
 
*/

 



answered Aug 24, 2025 by avibootz
0 votes
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.HashMap;
import java.util.Map;

class Main {
    public static void main(String[] args) {
        Map<String, String> map1 = Map.of("a", "aaa", "b", "bbb");
        Map<String, String> map2 = Map.of("b", "XYZ", "c", "ccc");

       Map<String, String> combined = Stream.of(map1, map2)
            .flatMap(map -> map.entrySet().stream())
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (v1, v2) -> v1 + "," + v2 // merge function for duplicate keys
        ));
        
        System.out.println(combined);
    }
}



/*
run:
 
{a=aaa, b=bbb,XYZ, c=ccc}
 
*/

 



answered Aug 24, 2025 by avibootz

Related questions

2 answers 105 views
2 answers 85 views
3 answers 92 views
2 answers 101 views
1 answer 72 views
...