Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 list to map with stream

I have a List<Item> collection. I need to convert it into Map<Integer, Item> The key of the map must be the index of the item in the collection. I can not figure it out how to do this with streams. Something like:

items.stream().collect(Collectors.toMap(...)); 

Any help?

As this question is identified as possible duplicate I need to add that my concrete problem was - how to get the position of the item in the list and put it as a key value

like image 332
Nikolay Avatar asked Sep 30 '15 06:09

Nikolay


People also ask

Can we use map stream in Java 8?

Java 8 Stream's map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream. It simply used to convert Stream of one type to another. Let's see method signature of Stream's map method.

Can we cast list to map in Java?

With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.

Can we use stream with map in Java?

Yes, you can map each entry to another temporary entry that will hold the key and the parsed integer value. Then you can filter each entry based on their value. Map<String, Integer> output = input.


1 Answers

You can create a Stream of the indices using an IntStream and then convert them to a Map :

Map<Integer,Item> map =      IntStream.range(0,items.size())              .boxed()              .collect(Collectors.toMap (i -> i, i -> items.get(i))); 
like image 84
Eran Avatar answered Sep 28 '22 02:09

Eran