Skip to content

Instantly share code, notes, and snippets.

@rayhon1014
Created March 29, 2017 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rayhon1014/a07e048245ead84b27c634278a7b5889 to your computer and use it in GitHub Desktop.
Save rayhon1014/a07e048245ead84b27c634278a7b5889 to your computer and use it in GitHub Desktop.
List<String> strList = Stream.of("1", "2", "illegal_3", "4", "illegal_5", "6").collect(Collectors.toList());
//return null and filter null
intList = strList.stream()// same with "parallelStream()"
.map(x -> {
try {
return Integer.parseInt(x);
} catch (NumberFormatException nfe) {
System.err.println(nfe.getMessage());
}
return null;
})
.filter(x -> x!= null)
.collect(Collectors.toList());
intList = strList.stream()
.flatMap(x -> parseIntStream(x))
.collect(Collectors.toList());
//return empty stream if error
static Stream<Integer> parseIntStream(String s) {
try {
return Stream.of(Integer.parseInt(s));
} catch (NumberFormatException nfe) {
System.err.println(nfe.getMessage());
}
return Stream.empty();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment