Skip to content

Instantly share code, notes, and snippets.

@phstudy
Created March 13, 2015 08:58
Show Gist options
  • Save phstudy/1e4f01597cebb19bbc4b to your computer and use it in GitHub Desktop.
Save phstudy/1e4f01597cebb19bbc4b to your computer and use it in GitHub Desktop.
side effect mapUsingReduce
public class MapApplication {
// case 1
public static <I, O> List<O> mapUsingCollect(Stream<I> stream, Function<I, O> mapper) {
return stream.collect(ArrayList::new, (acc, element) -> acc.add(mapper.apply(element)), ArrayList::addAll);
}
// case 2
public static <I, O> List<O> mapUsingReduce(Stream<I> stream, Function<I, O> mapper) {
return stream.reduce(new ArrayList<>(), (acc, element) -> {
ArrayList<O> newAcc = new ArrayList<>(acc);
newAcc.add(mapper.apply(element));
return newAcc;
}, (leftPartialResult, rightPartialResult) -> {
ArrayList<O> newLeftPartialResult = new ArrayList<>(leftPartialResult);
newLeftPartialResult.addAll(rightPartialResult);
return newLeftPartialResult;
});
}
// case 3
public static <I, O> List<O> mapUsingReduce2(Stream<I> stream, Function<I, O> mapper) {
return stream.reduce(new ArrayList<>(), (acc, element) -> {
acc.add(mapper.apply(element));
return acc;
}, (leftPartialResult, rightPartialResult) -> leftPartialResult);
}
public static void main(String[] args) {
System.out.println(mapUsingCollect(Stream.of(1, 2, 3, 4), x -> x + 1)); //[2, 3, 4, 5]
System.out.println(mapUsingCollect(Stream.of(1, 2, 3, 4).parallel(), x -> x + 1)); //[2, 3, 4, 5]
System.out.println(mapUsingReduce(Stream.of(1, 2, 3, 4), x -> x + 1)); //[2, 3, 4, 5]
System.out.println(mapUsingReduce(Stream.of(1, 2, 3, 4).parallel(), x -> x + 1)); //[2, 3, 4, 5]
System.out.println(mapUsingReduce2(Stream.of(1, 2, 3, 4), x -> x + 1)); //[2, 3, 4, 5]
System.out.println(mapUsingReduce2(Stream.of(1, 2, 3, 4).parallel(), x -> x + 1)); //[null, 3, 2, 4]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment