Stream API

Things that can be done using Stream API
1. Print a collection with some filter.
2. Get count of some collection with some filter.
3. Apply multiple filters over a collection.
4. Iterate over a list of array using streams.
5. Apply a logic to each element of collection using some function call and convert it into some new collection.
6. We can find the first element in a ordered collection or can return null.
7. Since forEach is terminal operation instead we can use peek() to return stream and perform operation on that.
8. Short circuiting using skip , limit etc.
9. Sort a Stream using sort() and compartor.
10. Can find min and max with just methods.
11. distinct to find distinct elements.
12. Short circuiting using allMatch, anyMatch and noneMatch()
13. Stream Specialization for primitive data type. IntStreamLongStream, and DoubleStream
14. sum(), average(), range()  to calculate, sum, average and range.

import java.util.Arrays;
import java.util.List;

public class StreamsDemo {
	public static void main(String[] args) {
		List<Persons> people = Arrays.asList(
								new Persons("Tyson","Gill",14),
								new Persons("Martin","Luther",15),
								new Persons("Sam","Watson",16),
								new Persons("Jake","Paul",12),
								new Persons("Duke","Logan",19),
								new Persons("Frost","Freenab",13),
								new Persons("Grin","Jaw",18),
								new Persons("Mak","Simsons",14)
								);
		people.stream()
		.filter(p -> p.getAge()>=15)
		.forEach(p -> System.out.println(p.getfName()));
	}
}
class Persons{
	Persons(String fName, String lName, int age){
		this.fName = fName;
		this.lName = lName;
		this.age = age;
	}
	String fName;
	public String getfName() {
		return fName;
	}
	public void setfName(String fName) {
		this.fName = fName;
	}
	public String getlName() {
		return lName;
	}
	public void setlName(String lName) {
		this.lName = lName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	String lName;
	int age;
}

A Guide to Streams in Java 8: In-Depth Tutorial with Examples

Leave a Comment