Another solution for completeness is to use a custom collector:
public static <T> Collector<T, ?, Map<Integer, T>> toMap() { return Collector.of(HashMap::new, (map, t) -> map.put(map.size(), t), (m1, m2) -> { int s = m1.size(); m2.forEach((k, v) -> m1.put(k+s, v)); return m1; }); }
Using:
Map<Integer, Item> map = items.stream().collect(toMap());
This solution is compatible with the parallel and is independent of the source (you can use a list without random access or Files.lines() or something else).
Tagir Valeev Sep 30 '15 at 10:41 2015-09-30 10:41
source share