Question:
Create a method which accepts an array of numbers and returns the numbers and their squares in an HashMap
Code:
import java.util.*; public class Example { public static HashMap method(int[] array) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int n: array) { map.put( n, n*n); } return map; } public static void main(String[] args) { int array[] = new int[]{1,2,3,4,5,6,7,8,9}; HashMap<Integer, Integer> map = method(array); Iterator<Integer> it = map.keySet().iterator(); while(it.hasNext()){ Integer key = it.next(); System.out.println(key + " : " + map.get(key)); } } }
Output:
$ java Example 1 : 1 2 : 4 3 : 9 4 : 16 5 : 25 6 : 36 7 : 49 8 : 64 9 : 81