Java stream API is the hot feature of java 8. Java stream represents a sequence of elements or objects and it supports different kind of operations to on it. Stream does not store elements.
It simply conveys the elements from
a source such as a data structure, an array, or an I/O channel, through a
pipeline of computational operations.
In the following examples, we have applied some operations with the help of stream:
- Filtering
Collection by using Stream
- Filtering
and Iterating Collection by using Stream
- reduce()
Method in Collection by using Stream
- Sum by
using Collectors Methods by using Stream
- Find
Max and Min Product Price by using Stream
- count()
Method in Collection by using Stream
- Convert
List into Set by using Stream
- Convert
List into Map by using Stream
We will use below book pojo class in all eample:
int id;
String name;
int price;
this.id = id;
this.name = name;
this.price = price;
}
}
Filtering Collection by using
Stream:
Our purpose is to construct a book name list from book list where price is less than 500. Example:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class StreamFilteringCollection {
List<Book1> booksList = new ArrayList<Book1>();
booksList.add(new Book1(1, "Learning J2SE", 100));
booksList.add(new Book1(2, "Learning J2EE", 200));
booksList.add(new Book1(3, "Learning C++", 300));
booksList.add(new Book1(4, "Learning Javascript", 400));
booksList.add(new Book1(5, "Learning Python", 500));
List<String> bookNameList1 = new ArrayList<String>();
for (Book1 book : booksList) {
int price = book.price;
String name = book.name;
if (price < 500) {
bookNameList1.add(name);
}
System.out.println("bookNameList using older java:" + bookNameList1 + "\r\n");
List<String> bookNameList2 = booksList.stream()
.filter(p -> p.price < 500).map(m -> m.name)
.collect(Collectors.toList());
}
Filtering and Iterating Collection by using Stream:
Our purpose is to iterating, filtering and passed a limit to fix the iteration on stream. Example:
import
java.util.stream.Stream;
public class StreamIterating {
Stream.iterate(1, element->element+1) .filter(element->element%5==0) .limit(5)
.forEach(System.out::println);
}
}
reduce() Method in Collection by using Stream:
The reduction operation combines all elements of the stream into a single result. For example, finding the sum of numbers, or accumulating elements into a list.
import java.util.ArrayList;
import
java.util.List;
public class StreamReduce {
List<Book> booksList = new ArrayList<Book>();
booksList.add(new Book(1,
"Learning J2SE", 100));
booksList.add(new Book(2,
"Learning J2EE", 200));
booksList.add(new Book(3,
"Learning C++", 300));
booksList.add(new Book(4,
"Learning Javascript", 400));
booksList.add(new Book(5,
"Learning Python", 500));
Integer totalPrice = 0;
// In
java older version
for (int i = 0; i < booksList.size(); i++) {
Book book = booksList.get(i);
totalPrice = totalPrice + book.price;
}
System.out.println("In java older version:totalPrice="+totalPrice);
// Using java8 stream API
totalPrice = booksList.stream().map(predicate -> predicate.price)
.reduce(0, (sum,price) -> sum + price);
System.out.println("Using java8 stream API:Approach 1: totalPrice = "+totalPrice);
totalPrice = booksList.stream().map(predicate -> predicate.price)
.reduce(0, Integer::sum);
System.out.println("Using java8 stream API:Approach 2: totalPrice = "+totalPrice);
}
}
Sum by using Collectors Methods by in
Stream:
In this example we will use collectors to compute sum of numeric values in stream api. Example:
import java.util.ArrayList;
import java.util.List;
import
java.util.stream.Collectors;
public class StreamSumByCollectors {
public static void main(String[] args) {
List<Book> booksList = new ArrayList<Book>();
// Adding Books
booksList.add(new Book(1, "Learning J2SE", 100));
booksList.add(new Book(2, "Learning J2EE", 200));
booksList.add(new Book(3, "Learning C++", 300));
booksList.add(new Book(4, "Learning Javascript", 400));
booksList.add(new Book(5, "Learning Python", 500));
Integer sumOfPrice = booksList.stream()
.collect(Collectors.summingInt(predicate -> predicate.price));
System.out.println("Sum of Book Price:"+sumOfPrice);
}
}
Find Max and Min Product Price by using Stream:
In this example we will lean how to use max and min of stream. We will find max price book object and min price book object using stream.
import java.util.ArrayList;
import
java.util.List;
public class StreamFindMaxMin {
public static void main(String[] args) {
List<Book> booksList = new ArrayList<Book>();
// Adding Books
booksList.add(new Book(1, "Learning J2SE", 100));
booksList.add(new Book(2, "Learning J2EE", 200));
booksList.add(new Book(3, "Learning C++", 300));
booksList.add(new Book(4, "Learning Javascript", 400));
booksList.add(new Book(5, "Learning Python", 500));
// Find max price book
Book bookMaxPrice = booksList.stream().max((b1,b2)->b1.price > b2.price ? 1:-1).get();
System.out.println("java8:Max Price Book: "+bookMaxPrice.name+","+bookMaxPrice.price);
// Find min price book
Book bookMinPrice = booksList.stream().min((b1,b2) -> b1.price > b2.price ? 1:-1).get();
System.out.println("java8:Min Price Book: "+bookMinPrice.name+","+bookMinPrice.price);
}
}
count() Method in Collection by using Stream:
Our target is to filter the list by price which is greater than 200 and return the count. Example:
import java.util.ArrayList;
import
java.util.List;
public class StreamFilterAndCount {
public static void main(String[] args) {
List<Book> booksList = new ArrayList<Book>();
//Adding
Books
booksList.add(new Book(1,"Learning J2SE",100));
booksList.add(new Book(2,"Learning J2EE",200));
booksList.add(new Book(3,"Learning C++",300));
booksList.add(new Book(4,"Learning Javascript",400));
booksList.add(new Book(5,"Learning Python",500));
long count = 0;
// In java older version
for (Book book : booksList) {
int ptice = book.price;
if(ptice > 200) {
count = count + 1;
}
}
System.out.println("In java older version: count = "+count);
// Using java8 stream API
count = booksList.stream().filter(predicate-> predicate.price > 200).count();
System.out.println("Using java8 stream API: count = "+count);
}
}
Convert List into Set by using Stream:
Our target is to filter the list by price and convert it into set. Example:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import
java.util.stream.Collectors;
public class StreamConvertListToSet {
public static void main(String[] args) {
List<Book> booksList = new ArrayList<Book>();
//Adding Books
booksList.add(new Book(1,"Learning J2SE",100));
booksList.add(new Book(2,"Learning J2EE",200));
booksList.add(new Book(3,"Learning C++",300));
booksList.add(new Book(4,"Learning Javascript",400));
booksList.add(new Book(5,"Learning Python",500));
Set<String> setList = new HashSet<String>();
// In java
older version
for (Book book : booksList) {
if(book.price > 200) {
setList.add(book.name);
}
}
System.out.println("In java older version:setList="+setList);
// Using java8 stream API
setList = booksList.stream().filter(predicate -> predicate.price > 200)
.map(predicate -> predicate.name)
.collect(Collectors.toSet());
System.out.println("Using java8 stream API:setList="+setList);
}
}
Convert List into Map by using Stream:
Our purpose is to convert a list into map and iterate the map and print the key value pair. Example:
public class StreamConvertListtoMap {
public static void main(String[] args) {
List<Book> booksList = new ArrayList<Book>();
//Adding Books
booksList.add(new Book(1,"Learning J2SE",100));
booksList.add(new Book(2,"Learning J2EE",200));
booksList.add(new Book(3,"Learning C++",300));
booksList.add(new Book(4,"Learning Javascript",400));
booksList.add(new Book(5,"Learning Python",500));
Map<Integer,String> bookPriceMap = new HashMap<Integer,String>();
// In java
older version
for (Book book : booksList) {
int key = book.id;
String value = book.name;
bookPriceMap.put(key, value);
}
for (Entry<Integer, String> entry : bookPriceMap.entrySet()) {
System.out.print("key-"+entry.getKey()+",value-"+entry.getValue()+"\r\n");
}
// Using java8 stream API
bookPriceMap = booksList.stream().collect(Collectors.toMap(p->p.id, p->p.name));
bookPriceMap.entrySet().forEach(m -> System.out.print("Java8:key-"+m.getKey()+",value-"+m.getValue()+"\r\n"));
}
}
Find distinct value:
List<String> distinctTeam = loginDataList.stream().filter(distinctByKey(p -> p.getTeam_name()))
.map(m -> m.getTeam_name()).collect(Collectors.toList());
public <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
To learn more about java 8 feature you can visit:
https://www.javatpoint.com/java-8-stream
https://www.baeldung.com/java-8-streams-introduction
No comments:
Post a Comment