Skip to content

Instantly share code, notes, and snippets.

@npathai
Created August 9, 2014 16:40
Show Gist options
  • Save npathai/42c53ffb2867d6072f9c to your computer and use it in GitHub Desktop.
Save npathai/42c53ffb2867d6072f9c to your computer and use it in GitHub Desktop.
This is a java counter part of map vs flatmap blogpost http://www.brunton-spall.co.uk/post/2011/12/02/map-map-and-flatmap-in-scala/
public class MapVsFlatMap {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3);
//Stream<X> --map (square)--> Stream<X>
list.stream()
.map(it -> it * 2)
.forEach(it -> System.out.println(it));
// Stream<X> --map--> Stream<Optional<X>> --filter--> Stream<Optional<X>> --each--> Print
list.stream()
.map(MapVsFlatMap::greaterThan2)
.forEach(optional -> {
System.out.println(optional);
});
//Stream<X> --map g(x)--> Stream<List<Integer>>
list.stream()
.map(MapVsFlatMap::g)
.forEach(it -> System.out.println(it));
list.stream()
.flatMap(it -> g(it).stream())
.forEach(it -> System.out.println(it));
list.stream()
.map(MapVsFlatMap::greaterThan2)
.filter(MapVsFlatMap::filterEmpty)
.forEach(it -> System.out.println(it));
}
public static List<Integer> g(Integer value) {
return Arrays.asList(value - 1, value, value + 1);
}
public static java.util.Optional<Integer> greaterThan2(Integer val) {
return val > 2 ? Optional.of(val) : Optional.empty();
}
public static <T> boolean filterEmpty(Optional<T> optional) {
return optional.isPresent();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment