int array to map java

https://‮ww‬w.lautturi.com
int array to map java

To convert an array of integers to a Map in Java, you can use the Collectors.toMap() method of the Collectors class. This method takes a function that specifies how to extract the key and value from each element of the array, and returns a Map that contains the keys and values extracted from the array elements.

Here is an example of how to convert an array of integers to a Map:

int[] arr = {1, 2, 3, 4, 5};

Map<Integer, Integer> map = Arrays.stream(arr)
    .boxed()
    .collect(Collectors.toMap(i -> i, i -> i * i));

// map is {1=1, 2=4, 3=9, 4=16, 5=25}

In this example, the array is first converted to a stream of integers using the Arrays.stream() method. The boxed() method is used to convert the stream of primitive int values to a stream of Integer objects. Finally, the Collectors.toMap() method is used to create a Map that contains the integers as both the keys and values, with the values being the squares of the keys.

For more information on the Collectors.toMap() method in Java, you can refer to the Java documentation.

Created Time:2017-11-01 22:29:53  Author:lautturi