Each key in a Map
can only point to a single entry, so you can't have a Map<String, String>
. But you can have a Map<String, List<String>>
("map from string to a list of strings"). This code will create a map whose keys come from the first list, and whose values are a list of all of the values from the second list.
public static void main(String[] args) {
List<String> eNode = Arrays.asList("ENB1", "ENB2", "ENB3", "ENB4",
"ENB5");
List<String> cloud = Arrays.asList("C1", "C2", "C3", "C4");
Map<String, List<String>> grouped = groupListsIntoMap(eNode, cloud);
System.out.println("Map:\n" + grouped);
}
public static Map<String, List<String>> groupListsIntoMap(List<String> keys,
List<String> values) {
int size = Math.min(keys.size(), values.size());
Map<String, List<String>> map = new HashMap<>();
for (int keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
String key = keys.get(keyIndex);
for (int valueIndex = 0; valueIndex < values.size(); ++valueIndex) {
map.computeIfAbsent(key, r -> new ArrayList<>()).add(values.get(
valueIndex));
}
}
return map;
}
This gives the output:
Map:
{ENB1=[C1, C2, C3, C4],
ENB2=[C1, C2, C3, C4],
ENB3=[C1, C2, C3, C4],
ENB4=[C1, C2, C3, C4],
ENB5=[C1, C2, C3, C4]}
Note that you should always declare the parameter type of a Java collection such as List
or Map
. Here it seems that your keys and values are always String
so we declare the lists as List<String>
("list of strings"). This enforces type safety and gives you a nice, clear compiler error if you try to add a non-string type to the list.
And if ENODE
and CLOUD
are mutable variables then you should name them in lowercase, with a name such as 'eNode' or 'enode'. This is known as a Java naming convention, and it makes it easier to read and review your code. If, on the other hand, these are static final
class fields then it is correct to give them an ALL_UPPERCASE_SEPARATED_BY_UNDERSCORES name, to show that they should be treated as constants (immutable, unmodifiable).