Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

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 89 views
2 answers 60 views
3 answers 80 views
2 answers 83 views
1 answer 61 views
...