Showing posts with label programs. Show all posts
Showing posts with label programs. Show all posts

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

Collection 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 a map from array in Java
      Convert an iterator to set in Java
      Convert an enumeration to set in Java
      Convert an enumeration to Iterable in Java
      Convert an array to set in Java
      Get the string representation of an Iterable
      Convert an Iterable to List in Java
      Convert an Iterable to a Set in Java
      Get the last element from a collection in Java
      Implement stack data structure using List
      Get a composite unmodifiable array list from two arrays
      Join the collection elements by a separator using streams
      Get the stream from an iterator in Java
      Get the stream from Enumeration in Java
      LinkedHashTable implementation in Java
      Get the enumeration from a Collection
      Get the enumeration from an Iterator in Java
      Get a map from enum in Java
      Construct a map from array of objects using streams
      Implement Multiset in Java