Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java 8, can I use streams to filter a partial string?

In Java 8, can I use streams to filter a partial string?

Let us assume I have a list of animals like:

Brown Bear
Black Bear
Black Crow
Red Herring 
Owl
Sparrow
Blackbacked Flocking Crow

Let us assume all of the Animals names are in a list of Animals Objects

public class Animal{
    public name;
    public animalType;
}

Is there some way to find all of the animals that have Black regardless of the case somewhere in the name. Something like the following...

List<Animal> filtList = employeeList.stream()
    .filter(x -> "%Black%".toUpperCase().equals(x.getLastName().toUpper()))
    .collect(Collectors.toList());
like image 536
Dale Avatar asked Apr 13 '17 17:04

Dale


People also ask

When we should not use streams in Java?

There are a few special cases where streams are hard to apply, like loop over 2 or 3 collections simultaneously. In such case streams make not much sense, for is preferable.

How do I filter a string in Java 8?

Using Java 8 In Java 8 and above, use chars() or codePoints() method of String class to get an IntStream of char values from the given sequence. Then call the filter() method of Stream for restricting the char values to match the given predicate.

Can we have multiple filter in stream Java?

2.1. Multiple Filters. The Stream API allows chaining multiple filters.


2 Answers

There is no toUpper() method for String.

It is toUpperCase() and also you need to use contains() to check "BLACK" there anywhere in the whole string, so the code should be simple as shown below:

List<Employee> filtList = inputList.stream().
         filter(value -> value.toUpperCase().//convert to uppercase for checking
         contains("BLACK")).//filter values containing black
         collect(Collectors.toList());//collect as list
like image 197
developer Avatar answered Sep 23 '22 02:09

developer


Use regex:

List<Animal> filtList = list.stream()
   .filter(x -> x.getName().matches("(?i).*black.*"))
   .collect(Collectors.toList());

The regex flag "(?)" means "ignore case".

like image 24
Bohemian Avatar answered Sep 27 '22 02:09

Bohemian