user3878073
user3878073

Reputation: 91

create a Map from int array with index as key and value as array element in java

this is a integer array I have

[9,3,15,20,7]

I want to create a map like

0->9 1->3

with index as key and array element as value

IntStream.range(0,postorder.length).collect(Collectors.toMap(i -> postorder[i],i->i));

I tried like this but getting compilation error as required type int found object is there any to create map like this using streams in java

Upvotes: 0

Views: 2096

Answers (2)

Aditya Rewari
Aditya Rewari

Reputation: 2707

You should have boxed() the IntStream

final int[] postorder = {2,5, 6, 8};
Map<Object, Object> map = IntStream
        .range(0,postorder.length)
        .boxed()
        .collect(Collectors.toMap(index -> index, index-> postorder[index]));
System.out.println(map);

Upvotes: 2

ZIHAO LIU
ZIHAO LIU

Reputation: 387

IntStream.range(0, postorder.length)
         .boxed()
         .collect(Collectors.toMap(i -> i, i -> postorder[i], (a, b) -> b));

Upvotes: 1

Related Questions