Harness the power of java 8 Streams
Why should i use streams, what are java 8 streams and what are they good for?
First of all, what problem do they solve?
There is a lot of talk about maintainability and readability of code and streams are a neat little thing to do just that.
But lets see ourselves with an example.
Car car1 = new Car(“Blue”,”BMW x3",1);Car car2 = new Car(“Black”,”Volkswagen Passat”,2);Car car3 = new Car(“Red”,”Ferrari Spider”,3);List<Car> listOfCars = new ArrayList<Car>();listOfCars.add(car1);listOfCars.add(car2);listOfCars.add(car3);
If i have this regular java ArrayList and i want to get a certain car i can usually only do something like this:
Car myDreamCar = listOfCars.get(0);
Here i can only get my car by index. So i need to know which car i want already. But what if thats the car my mum chose? What if i want to choose exactly the car i want and add it to the list of my dreamcars? Let see:
List<Car> filteredListOfMyDreamCars = listOfCars.stream().filter(car -> car.equals(car1)).collect(Collectors.toList());
That might on the first look, look much more confusing than it actually is.
Lets go through it bit by bit.
First we turn the list into a stream:
listOfCars.stream()
Then we use the filter method on this stream and only find the entries in the list we want:
listOfCars.stream().filter(car -> car.equals(car1))
Then we collect it into a list:
listOfCars.stream().filter(car -> car.equals(car1)).collect(Collectors.toList())
Voila. Thats all we needed to do.
What else can we do with streams?
Well lets check if there are even any results in the List.
Optional<Car> result = listOfCars.stream().findAny();result.isPresent();
result.isPresent() will return us a boolean that indicates wether the list has a value or not. Very useful to check a if a list has values before we try to read from it to avoid any weird error messages.
If youre asking what are optionals then i will try to write an article in the future. If you are interested leave a comment below.
What if i want to specifically choose the car with the id 2 now? Also very simple.
You can write a so called predicate.
Predicate<Car> predicate1 = c -> c.getID() ==2;
This predicate will return all cars with the id 2. This predicate can be used in a stream now:
Predicate<Car> predicate1 = c -> c.getID() ==2;listOfCars.stream().anyMatch(predicate1);
or in a short form:
listOfCars.stream().anyMatch(c -> c.getID() ==2);
This expression will return a boolean wether a car with id == 2 is in the list.
This are just some possibilities streams offer now that make programming easier and more convenien.
If you have any questions you want to have answered about streams just ask away.