Friday 11 November 2022

Get a map from array in Java

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

Interview Questions

Collection programs in Java

Array programs in Java

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

Get reverse iterator for the given array in Java

Convert primitive array to wrapper array in Java

No comments:

Post a Comment