Skip to content

Instantly share code, notes, and snippets.

@rokon12
Created August 15, 2020 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rokon12/4ce938da81fa213835893db2550187c2 to your computer and use it in GitHub Desktop.
Save rokon12/4ce938da81fa213835893db2550187c2 to your computer and use it in GitHub Desktop.
Stream
package com.masterdevskills.stream.collect;
public class Author {
private String firstName;
private String lastName;
public Author(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public Author setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public String getLastName() {
return lastName;
}
public Author setLastName(String lastName) {
this.lastName = lastName;
return this;
}
}
package com.masterdevskills.stream.collect;
import java.util.Random;
enum BookGenres {
REALISTIC_FICTION,
HISTORICAL_FICTION,
HUMOR,
MYSTERY,
YOUNG_ADULT_FICTION,
REFERENCE_BOOK
}
public class Book {
private String name;
private int price;
private Author author;
private boolean fiction;
private BookGenres bookGenres;
private int rating;
public Book(String name, int price, Author author, boolean fiction, BookGenres bookGenres) {
this.name = name;
this.price = price;
this.author = author;
this.fiction = fiction;
this.bookGenres = bookGenres;
this.rating = new Random().nextInt(5) + 1;
}
public String getName() {
return name;
}
public Book setName(String name) {
this.name = name;
return this;
}
public int getPrice() {
return price;
}
public Book setPrice(int price) {
this.price = price;
return this;
}
public Author getAuthor() {
return author;
}
public Book setAuthor(Author author) {
this.author = author;
return this;
}
public boolean isFiction() {
return fiction;
}
public Book setFiction(boolean fiction) {
this.fiction = fiction;
return this;
}
public BookGenres getBookGenres() {
return bookGenres;
}
public Book setBookGenres(BookGenres bookGenres) {
this.bookGenres = bookGenres;
return this;
}
public int getRating() {
return rating;
}
public Book setRating(int rating) {
this.rating = rating;
return this;
}
@Override
public String toString() {
return name;
}
}
package com.masterdevskills.stream.collect;
import java.util.List;
import static com.masterdevskills.stream.collect.BookGenres.*;
public interface BookService {
default List<Book> createBooks() {
var hAhmed = new Author("Humayun", "Ahmed");
var zIqbal = new Author("Zafor", "Iqbal");
return List.of(
new Book("Nondito Noroke", 90, hAhmed, true, REALISTIC_FICTION),
new Book("Deyal", 323, hAhmed, true, HISTORICAL_FICTION),
new Book("Hijibiji", 213, hAhmed, true, HUMOR),
new Book("Elebele", 90, hAhmed, true, HUMOR),
new Book("Misir Ali Unsolved", 114, hAhmed, true, MYSTERY),
new Book("Nat Baltu", 132, zIqbal, true, YOUNG_ADULT_FICTION),
new Book("Ami Topu", 132, zIqbal, true, YOUNG_ADULT_FICTION),
new Book("Amar Bondhu Rashed", 141, zIqbal, true, HISTORICAL_FICTION),
new Book("Theory of Relativity", 154, zIqbal, false, REFERENCE_BOOK),
new Book("Quantum Mechanics", 141, zIqbal, false, REFERENCE_BOOK)
);
}
}
package com.masterdevskills.stream.collect;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.*;
public class BookServiceImpl implements BookService {
public static void main(String[] args) {
// count all books
var bookService = new BookServiceImpl();
List<Book> books = bookService.createBooks();
long count = books
.stream()
.filter(book -> book.getBookGenres() == BookGenres.REFERENCE_BOOK)
.count();
books.stream()
.filter(book -> book.getBookGenres() == BookGenres.REFERENCE_BOOK)
.mapToInt(Book::getPrice)
.sum();
Integer sum = books.stream()
.filter(book -> book.getBookGenres() == BookGenres.REFERENCE_BOOK)
.collect(summingInt(Book::getPrice));
IntSummaryStatistics statistics = books.stream()
.collect(summarizingInt(Book::getPrice));
double average = statistics.getAverage();
String bookCommaSeparated
= books.stream()
.map(Book::getName)
.collect(joining(", "));
System.out.println(bookCommaSeparated);
Map<BookGenres, List<Book>> map = books.stream()
.collect(groupingBy(Book::getBookGenres));
Map<Author, String> collect = books.stream()
.filter(book -> book.getPrice() > 400)
.collect(toMap(Book::getAuthor, Book::getName, (a, b) -> a + "," + b));
Map<Rating, List<Book>> listMap = books.stream()
.collect(groupingBy(BookServiceImpl::getRating));
System.out.println(map);
}
private static Rating getRating(Book book) {
if (book.getRating() <= 2) {
return Rating.LOW;
} else if (book.getRating() > 2 && book.getRating() <= 4) {
return Rating.MEDIUM;
} else {
return Rating.HIGH;
}
}
}
package com.masterdevskills.stream.collect;
public enum Rating {
LOW, MEDIUM, HIGH
}

#summarizing

  1. count all the books
  2. find the count of reference book
  3. find the prices of all reference book in total
  4. find the average book price in this store. hints: IntSummeryStatistics

#StringJoining 5. find the name of all the books comma separated

#grouping 6. group books by genres 7. Group by rating - low, medium, and high rating -> collect(groupBy(book -> { })) 8. group genres by counting -> collect (groupBy(Book::Genres, counting)) 9. group author by its costly book -> collect(groupBy(author, maxBy(comparator))

#partitioning 10. partition by fiction/non-fiction

package com.masterdevskills.stream;
import java.math.BigDecimal;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.IntStream;
public class Demo {
public static void main(String[] args) {
var transactionList
= FakeTransactionGenerator.generate(1_000_000);
calculateTime(() -> processInSequential(transactionList), "Sequential Calculation: ", 10);
calculateTime(() -> processInParallel(transactionList), "parallel Calculation: ", 10);
}
public static BigDecimal processInParallel(List<Transaction> transactions) {
return transactions
.parallelStream()
.filter(Transaction::isCredit)
.map(Transaction::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
public static BigDecimal processInSequential(List<Transaction> transactions) {
return transactions
.stream()
.filter(Transaction::isCredit)
.map(Transaction::getAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
public static void calculateTime(Supplier<BigDecimal> supplier,
String name, int iteration) {
System.out.println("\nStarting: " + name);
var statistics = IntStream.range(0, iteration)
.mapToLong(value -> exectue(supplier, value))
.summaryStatistics();
System.out.println("\nTime to complete in " + name + " is: ");
System.out.println("Average: " + statistics.getAverage() + " msecs");
System.out.println("Maximum: " + statistics.getMax() + " msecs");
System.out.println("Minimum: " + statistics.getMin() + " msecs");
}
private static long exectue(Supplier<BigDecimal> supplier, int value) {
long start = System.nanoTime();
supplier.get();
long duration = (System.nanoTime() - start);
long msecs = (duration / 1_000_000);
System.out.println("Iteration: " + value
+ ", execution time: " + msecs);
return msecs;
}
}
package com.masterdevskills.stream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class FakeTransactionGenerator {
public static List<Transaction> generate(int size) {
Random random = new Random();
return IntStream.range(0, size)
.mapToObj(value -> createTransaction(random))
.collect(Collectors.toList());
}
private static Transaction createTransaction(Random random) {
var uuid = UUID.randomUUID().toString();
var isCredit = random.nextBoolean();
var amount = getRandomAmount(BigDecimal.TEN, BigDecimal.valueOf(1000_000));
return new Transaction(uuid, isCredit, amount);
}
private static BigDecimal getRandomAmount(BigDecimal min, BigDecimal max) {
var randomBigDecimal
= min.add(BigDecimal.valueOf(Math.random())
.multiply(max.subtract(min)));
return randomBigDecimal.setScale(2, RoundingMode.UP);
}
}
package com.masterdevskills.stream;
import java.math.BigDecimal;
public class Transaction {
private String transactionId;
private boolean credit;
private BigDecimal amount;
public Transaction(String transactionId, boolean credit, BigDecimal amount) {
this.transactionId = transactionId;
this.credit = credit;
this.amount = amount;
}
public String getTransactionId() {
return transactionId;
}
public boolean isCredit() {
return credit;
}
public BigDecimal getAmount() {
return amount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment