Skip to content

Instantly share code, notes, and snippets.

@AravindaM
Last active June 30, 2022 16:43
Show Gist options
  • Save AravindaM/5819caf2f5d45bf844c30ef95eec0f84 to your computer and use it in GitHub Desktop.
Save AravindaM/5819caf2f5d45bf844c30ef95eec0f84 to your computer and use it in GitHub Desktop.
[Java snippet - 1 ] Filter an entry from a stream .flatMap vs .mapMulti in java

How to filter an entry from a stream in Java

1. Using .flatmap

List<Integer> numbers = listOfStrings.stream()
        .flatMap(s -> {
            try {
                return Stream.of(Integer.parseInt(s));
            } catch (Exception e) {
                return Stream.of();
            }
        }).toList();

2. Using .mapMulti introduced in java 16.

  List<Integer> numbers = listOfStrings.stream()
          .<Integer>mapMulti((s, consumer) -> {
              try {
                  consumer.accept(Integer.parseInt(s));
              } catch (Exception e) {
                //ignored
              }
          }).toList();

Comment! Share! Support!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment