0

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

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

this worked can you explain about this I can't understand the (a, b) -> b) part
In your case, you can remove (a, b) -> b part, .collect(Collectors.toMap(i -> i, i -> postorder[i]); will works as well. (a, b) -> b) is a merge function, it will be used if there is duplicate key of map. In your case it can be ignored. You can see the api doc docs.oracle.com/javase/8/docs/api/java/util/stream/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.