Input: array of values like below.
key1, value1, key2, value2, ……keyN, valueN
Output: Get a map out of the array.
key1 -> value1, key2 -> value2, ……… ……… keyN -> valueN
MapFromArray.java
package com.sample.app.collections;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class MapFromArray {
public static Map<Object, Object> toMap(final Object... elements) {
if (elements == null) {
return Collections.emptyMap();
}
final int noOfElements = elements.length;
if (noOfElements % 2 != 0) {
throw new IllegalArgumentException("Number of elements must be an even number to form a map");
}
final Map<Object, Object> map = new HashMap<>(noOfElements / 2);
int i = 0;
while (i < elements.length - 1) {
map.put(elements[i++], elements[i++]);
}
return map;
}
public static void main(String[] args) {
Object[] empsInfo = { 1, "Krishna", 2, "Ram", 3, "PTR" };
Map<Object, Object> map = toMap(empsInfo);
System.out.println(map);
}
}
Output
{1=Krishna, 2=Ram, 3=PTR}
You may like
How to check the object is an iterable or not?
How to check the type or object is a map or not?
Get an iterator from array in Java
No comments:
Post a Comment