In this tutorial, we will see Java Stream Filter() with examples in different uses such as collect(), findAny(), anyMatch(), and map(), all thanks to Java streams.
Streams were introduced with Java 8. In the following examples, we will see how it was done before Java 8 and how we can do it using streams.
Use filter() and collect() with Java Stream
In the following example, we will write the car that is blue:
Filter without Streams
package com.refactorizando.streams; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class BeforeStreams { public static void main(String[] args) { List<String> colorCars = Arrays.asList("blue", "red", "green"); List<String> colors = getColorBlue(colorCars); for (String color : colors) { System.out.println(color); } } private static List<String> getColorBlue(List<String> colorCars) { List<String> colors = new ArrayList<>(); for (String color : colorCars) { if ("blue".equals(color)) { colors.add(color); } } return colors; } }
Output:
blue
Filter with stream() in Java
package com.refactorizando.streams; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class WithStreams { public static void main(String[] args) { List<String> colorCars = Arrays.asList("blue", "red", "green"); List<String> colorBlue = colorCars.stream() .filter(color -> "blue".equals(color)) .collect(Collectors.toList()); result.forEach(System.out::println); } }
Output:
blue
In the previous example, we saw how we can traverse a list using streams, and we filter out the items that match a certain criterion.
Use of findAny() and findFirst() with Java Stream and examples
For the following example, we will keep searching for the blue color in a car, but we will have several cars and several blue colors.
To do that, we first define the car object.
package com.refactorizando.streams; @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class Car { private String model; private String color; public List<Car> createCars() { return Arrays.asList( new Car("Mazda", "Red"), new Car("Seat", "Blue"), new Car("Audi", "Blue") ); } }
Filter without stream
In this case, we will find any car that has a blue color.
package com.refactorizando.streams; import java.util.Arrays; import java.util.List; public class BeforeStreams { public static void main(String[] args) { Car car = new Car(); List<Car> cars = car.createCars(); Car carResult = getBlueCars(cars); System.out.println(carResult); } private static Car getBlueCars(List<Car> cars) { Car car = null; for (Car c : cars) { if ("blue".equalsIgnoreCase(c.getColor())) { car = c; } } return car; } }
Output:
Car{model='Audi', color='Blue'}
Streams with filter() and findAny()
With findAny(), we will find any car that has a blue color, once it passes the filter.
package com.refactorizando.streams; import java.util.Arrays; import java.util.List; public class WithStreams { public static void main(String[] args) { Car car = new Car(); List<Car> cars = car.createCars(); Optional<Car> colorCar = cars.stream() .filter(c -> "blue".equalsIgnoreCase(c.getColor())) .findAny(); System.out.println(colorCar.orElseThrow()); } }
Output:
Car{model='Audi', color='Blue'}
Streams with filter() and findFirst()
The difference between findFirst() and findAny() is that with the first one we will find the first value that meets the filter, and with the second one any value.
package com.refactorizando.streams; import java.util.Arrays; import java.util.List; public class WithStreams { public static void main(String[] args) { Car car = new Car(); List<Car> cars = car.createCars(); Optional<Car> colorCar = cars.stream() .filter(c -> "blue".equalsIgnoreCase(c.getColor())) .findFirst(); System.out.println(colorCar.orElseThrow()); } }
Output:
Car{model='Seat', color='Blue'}
Streams with filter(), Map() and findAny()
Map in a Java stream gives us the possibility to convert one type of object into another, or work with the object that we have received. It is easiest to understand with an example:
package com.refactorizando.streams; import java.util.Arrays; import java.util.List; public class WithStreamsMap { public static void main(String[] args) { Car car = new Car(); List<Car> cars = car.createCars(); String modelCar = cars.stream() .filter(c -> "blue".equalsIgnoreCase(c.getColor())) .map(Car::getModel) .findAny() //si utilizamos findFirst() obtenemos el primero .orElseThrow() //throw an exception if does not exist value. System.out.println(modelCar); List<String> carsByColorBlue = cars.stream() .filter(c->"blue".equalsIgnoreCase(c.getColor())) .map(Car::getModel) .collect(Collectors.toList()); carsByColorBlue.forEach(System.out::println); } }
Output modelCar:
Audi
Output carsByColorBlue:
Seat Audi
Debug and logging of Streams
In many occasions when we are working with Java Streams, we may wonder how we can do logging or debugging on that stream. For these cases, the best way and the one provided by the Streams API is by using Peek.
It is important to note that the use of Peek is as an intermediate operation only. And what the official documentation tells us is that its use is exclusive to debugging, so any other approach is discouraged.
Stream.of("apple", "orange", "cherry", "banana") .filter(e -> e.length() > 6) .peek(e -> System.out.println("Fruits are : " + e)) .map(String::toUpperCase) .peek(e -> System.out.println("Now are upperCase " + e)) .collect(Collectors.toList());
Although we could achieve the same thing with map and peek, the purpose of peek is solely for debugging in our streams.
Conclusion
In this post we have seen how filter() works in streams with Java and some examples to process the stream, such as findFirst(), findAny(), and map(). However, if you want to delve deeper, it would be good to take a look at the following tutorial: https://www.oracle.com/technetwork/es/articles/java/procesamiento-streams-java-se-8-2763402-esa.html
If you need more information, you can leave us a comment or send an email to refactorizando.web@gmail.com You can also contact us through our social media channels on Facebook or twitter and we will be happy to assist you!!