Converting string arrays into Map
I have two string arrays keys and values
String[] keys = {a,b,c,d};
String[] values = {1,2,3,4};
What is the fastest way to convert them into a map? I know we can iterate through them. But, is there any utility present?
Faster than this?
Map<String,String> map = new HashMap<>();
if(keys.length == values.length){
for(int index = 0; index < keys.length; index++){
map.put(keys[index], values[index]);
}
}
I purpose to you two very simple implementations. One with stream Api of Java 8, one without.
Java < 8 (without stream api)
if(keys.length != values.length) {
throw new IllegalArgumentException("Keys and Values need to have the same length.");
}
Map<String,String> map = new HashMap<>();
for (int i = 0; i < keys.length; i++) {
map.put(keys[i], values[i]);
}
Java > 8 (with stream api)
if(keys.length != values.length) {
throw new IllegalArgumentException("Keys and Values need to have the same length.");
}
Map<String,String> map = IntStream.range(0, keys.length).boxed()
.collect(Collectors.toMap(i -> keys[i], i -> values[i]));