Tal
Tal

Reputation: 15

How filter java stream by a list of strings without using a for loop

I have a List<LogEntry> that I need to filter out from the list every log that is not on Level.SEVERE. And in addition I have a List of whitelisted logs that need to be filtered too. These logs are contains only partial message so I have to use contains() to identified them.

My code looks like this:

LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
List<LogEntry> logEntriesList = logEntries.getAll();

Stream<LogEntry> filtered =
    logEntriesList.stream()
                  .filter(log -> log.getLevel().equals(Level.SEVERE));
    
for (String whitelisted : whitelistedLogs) {
    filtered = filtered.filter(log -> !log.getMessage().contains(whitelisted));
}

Is there any way to avoid this for loop and get the same result?

Upvotes: 1

Views: 214

Answers (2)

user7571491
user7571491

Reputation:

If whitelisted logs are constant, instead of list, you could create a regex from them one time. That way you could:

filtered = filtered.filter(log -> !log.getMessage().matches(whitelisted_regex));

Upvotes: 0

Gautham M
Gautham M

Reputation: 4935

First you filter those with SEVERE log level, then filter those which contains at least one whitelisted message:

logEntriesList.stream()
              .filter(log -> log.getLevel().equals(Level.SEVERE))
              .filter(log -> whitelistedLogs.stream().noneMatch(wl -> log.getMessage().contains(wl)))
              .collect(Collectors.toList());

Upvotes: 1

Related Questions