stream optional if present anymatch code example

Example 1: optional throw if present

Optional.of(usuarios.findByEmail(usuario.getEmail())).ifPresent(param -> {
      throw new IllegalArgumentException("Only Strings allowed in path parameters.")
    });

Example 2: stream optional if present anymatch

List<Optional<String>> listOfOptionals = Arrays.asList(
  Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));

Example 3: stream optional if present anymatch

List<String> filteredList = listOfOptionals.stream()
  .filter(Optional::isPresent)
  .map(Optional::get)
  .collect(Collectors.toList());

Tags:

Misc Example