|
| 1 | +package com.baeldung.combiningcollections; |
| 2 | + |
| 3 | +import java.util.Collection; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.Map; |
| 6 | +import java.util.stream.Collectors; |
| 7 | +import java.util.stream.Stream; |
| 8 | + |
| 9 | +import org.apache.commons.exec.util.MapUtils; |
| 10 | + |
| 11 | +import com.google.common.collect.ImmutableMap; |
| 12 | + |
| 13 | +public class CombiningMaps { |
| 14 | + |
| 15 | + public static Map<String, String> usingPlainJava(Map<String, String> first, Map<String, String> second) { |
| 16 | + Map<String, String> combined = new HashMap<>(); |
| 17 | + combined.putAll(first); |
| 18 | + combined.putAll(second); |
| 19 | + return combined; |
| 20 | + } |
| 21 | + |
| 22 | + public static Map<String, String> usingJava8ForEach(Map<String, String> first, Map<String, String> second) { |
| 23 | + second.forEach((key, value) -> first.merge(key, value, String::concat)); |
| 24 | + return first; |
| 25 | + } |
| 26 | + |
| 27 | + public static Map<String, String> usingJava8FlatMaps(Map<String, String> first, Map<String, String> second) { |
| 28 | + Map<String, String> combined = Stream.of(first, second).map(Map::entrySet).flatMap(Collection::stream) |
| 29 | + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, String::concat)); |
| 30 | + return combined; |
| 31 | + |
| 32 | + } |
| 33 | + |
| 34 | + public static Map<String, String> usingApacheCommons(Map<String, String> first, Map<String, String> second) { |
| 35 | + Map<String, String> combined = MapUtils.merge(first, second); |
| 36 | + return combined; |
| 37 | + } |
| 38 | + |
| 39 | + public static Map<String, String> usingGuava(Map<String, String> first, Map<String, String> second) { |
| 40 | + Map<String, String> combined = ImmutableMap.<String, String>builder() |
| 41 | + .putAll(first) |
| 42 | + .putAll(second) |
| 43 | + .build(); |
| 44 | + return combined; |
| 45 | + } |
| 46 | + |
| 47 | +} |
0 commit comments