fork download
  1. import java.util.Arrays;
  2. import java.util.List;
  3. import java.util.Optional;
  4. import java.util.function.Function;
  5. import java.util.stream.Collectors;
  6.  
  7. public final class Main {
  8.  
  9. private static <T, U> List<U> compactMap(
  10. List<T> list,
  11. Function<T, Optional<U>> transform) {
  12. return list.stream()
  13. .map(e -> transform.apply(e))
  14. .flatMap(o -> o.stream())
  15. .collect(Collectors.toList());
  16. }
  17.  
  18. public static void main(String[] args) {
  19. var list = Arrays.asList(
  20. "The", "quick", "brown", null, "jumps",
  21. "over", "the", "lazy", null);
  22. var all = compactMap(
  23. list,
  24. e -> Optional.ofNullable(e)
  25. .map(s -> Integer.valueOf(s.length())));
  26. for (var e : all) {
  27. System.out.println(e);
  28. }
  29. }
  30. }
  31.  
Success #stdin #stdout 0.09s 33888KB
stdin
Standard input is empty
stdout
3
5
5
5
4
3
4