Filtering a non integer in a list of strings

java-8, java-stream

Solution

You don’t need the `FileInputStream` > `InputStreamReader` > `BufferedReader` detour to get a stream of lines. Even if you need a `BufferedReader`, there’s `Files.newBufferedReader`

Don’t manipulate an existing collection within `forEach`; if you fall back to that, you better stay with the ordinary loop. For Stream’s, there is `flatMap` to process nested items, e.g. tokens within a line

The tokens itself can be filtered with a simple regular expression, `[0-9]+` implies that there must be at least one digit, which also sorts out empty strings, but using `" *"` as split pattern rather than `" "`, empty strings are not even created in the first place. `null` never occur as a result of the split operation

List<Integer> allValues;
try(Stream<String> lines=Files.lines(file.toPath())) {
    allValues=lines.flatMap(Pattern.compile(" *")::splitAsStream)
         .filter(s -> s.matches("[0-9]+"))
         .map(Integer::valueOf)
         .collect(Collectors.toList());
}

Problem

I am reading a file and forming a integer list. Example file: ``` 1 1 2 3 4 2 2 5 abc 4 2 8 ``` On running the below code it fails because of "abc"cannot be converted to an Integer. Could you please let me know if it is possible to filter out the non integer fields in a cleaner way in Java 8 Eg: Using filters? ``` try (BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(file)))) { List<Integer> allValues = new ArrayList<>(); br.lines().forEach( strLine -> { List<String> wordsList = Arrays.asList(strLine.trim().split(" ")); List<Integer> routes = wordsList.stream() .filter(e -> e != null && !e.isEmpty()) .map(Integer::valueOf) .collect(Collectors.toList()); allValues.addAll(routes); }); allValues.forEach(str -> System.out.print(str)); } ```

Original source