Skip to content

Instantly share code, notes, and snippets.

@neversleepz
Created December 12, 2016 04:41
Show Gist options
  • Save neversleepz/58c69747657b1869b638e9fe5e75311a to your computer and use it in GitHub Desktop.
Save neversleepz/58c69747657b1869b638e9fe5e75311a to your computer and use it in GitHub Desktop.
Made this for a colleague. An arguably, improved way to use streams api to parse a collection, providing the index (for failure messages)
package org.outrospective.streams;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ListToIndexedMapBuilder {
public static void main(String[] args) {
new ListToIndexedMapBuilder();
}
public ListToIndexedMapBuilder() {
List<String> originalCollection = Arrays.asList("foo", "bar", "scar", "mars", "bars", "bar");
ConcurrentMap<Integer, String> indexedList = indexedList(originalCollection);
System.out.println("indexedList = " + indexedList);
}
public static ConcurrentMap<Integer, String> indexedList(List<String> list) {
return IntStream.range(0, list.size())
// the next two lines aren't req'd but:
.parallel() // I was curious if for a large enough list parallel would be better
.unordered() // Making the stream unordered would allow for better parallelisation potentially
.boxed()
.collect(Collectors.toConcurrentMap( // toMap could have been ok here too
Function.identity(),
list::get));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment