Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use filter in Java 8 to ignore values from an int array and to collection

I have a list of errorCodes which I want to check whether or not they contain error codes in a separate array. If the error codes exist in list errorCode then I want to filter those out.

This is what I have so far

int[] ignoredErrorCodes = {400, 500};

  List<Error> errorCodes = errorsList.stream()
            .filter(error -> error.getErrorCode() != ignoredErrorCodes[0])
            .collect(Collectors.toList());

how can I check against all values in the array ignoredErrorCodes instead of just one, using streams?

like image 737
user6248190 Avatar asked Mar 05 '23 05:03

user6248190


1 Answers

It would be better to store the ignoreds codes in a Set for faster lookup:

Set<Integer> ignored = Set.of(400,500);
List<Error> errorCodes = errorsList.stream()
            .filter(error -> !ignored.contains(error.getErrorCode()))
            .collect(Collectors.toList());
like image 130
Eran Avatar answered Mar 12 '23 16:03

Eran