I have a list of objects. I want to do the following
for (int i = 0; i < sorted.size(); i++) {
map.put(i, sorted.get(i).getName());
}
Is there a straightforward way to do this in Java 8 streams api ?
You can do the following:
Map<Integer, String> map =
IntStream.range(0, sorted.size())
.boxed()
.collect(toMap(i -> i, i -> sorted.get(i).getName()));
This creates a Stream of int
going from 0 to the size of list and collects each value into a Map.
Since you want to collect the elements into a data structure which intrinsically tracks the position as its size, you can do the operation using a custom collector:
Map<Integer, String> map=sorted.stream()
.map(x -> x.getName())
.collect(HashMap::new, (m,s) -> m.put(m.size(), s),
(a,b) -> { int off=a.size(); b.forEach((i,s) -> a.put(i+off, s));});
The trickiest part is the merge function which will be used in parallel processing only. It adds all elements of a map to its preceding map, but has to offset the keys by the number of preceding elements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.