Skip to content

Instantly share code, notes, and snippets.

@golonzovsky
Last active December 16, 2017 11:56
Show Gist options
  • Save golonzovsky/ec25d96ae559738b7381 to your computer and use it in GitHub Desktop.
Save golonzovsky/ec25d96ae559738b7381 to your computer and use it in GitHub Desktop.
lambda
package com.golonzovsky.streams;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.junit.Before;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.time.Year;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamsTest {
private List<Book> library;
@Before
public void setUp() throws Exception {
Book nails = new Book("Fundamentsls of nail image", Arrays.asList("Li", "Fu", "Li"), new int[]{256}, Year.of(2014), 25.2, Topic.MEDICINE);
Book dragon = new Book("Compilers: Principles, Techniques and Tools", Arrays.asList("Aho", "Lam", "Li"), new int[]{1009}, Year.of(2006), 23.6, Topic.COMPUTING);
Book voss = new Book("Voss", Arrays.asList("Patrick white"), new int[]{478}, Year.of(1957), 29.8, Topic.FICTION);
Book lotr = new Book("Lord Of The Rings", Arrays.asList("Tolkien"), new int[]{531, 416, 624}, Year.of(1955), 23.0, Topic.FICTION);
Book history = new Book("Ancient History", Arrays.asList("Likonov", "Sokolsky"), new int[]{578}, Year.of(1979), 28.0, Topic.HISTORY);
library = Arrays.asList(nails, dragon, voss, lotr, history);
}
@Test
public void testStreams() throws Exception {
Stream<Book> computingBooks = library.stream()
.filter(b -> b.getTopic() == Topic.COMPUTING);
Stream<String> bookTitles = library.stream()
.map(Book::getTitle);
Stream<Book> booksSortedByTitle = library.stream()
.sorted(Comparator.comparing(Book::getTitle));
//distinct authors in order of book titles
Stream<String> authors = library.stream()
.sorted(Comparator.comparing(Book::getTitle))
.flatMap(b -> b.getAuthors().stream())
.distinct();
Stream<Book> first100inAlphabetical = library.stream().sorted(Comparator.comparing(Book::getTitle))
.limit(100);
Stream<Book> rest100inAlphabetical = library.stream().sorted(Comparator.comparing(Book::getTitle))
.skip(100);
Optional<Book> firstPublished = library.stream()
.sorted(Comparator.comparing(Book::getYear))
.findFirst();
int totalAuthors = library.stream().mapToInt(b -> b.getAuthors().size()).sum();
int totalPageCount1 = library.stream().flatMapToInt(b -> Arrays.stream(b.getPageCount())).sum();
int totalPageCount2 = library.stream().flatMapToInt(b -> IntStream.of(b.getPageCount())).sum();
List<Book> multipleAuthoredHistories = library.stream()
.filter(b -> b.getTopic() == Topic.HISTORY)
.peek(b -> System.out.println(b.getTitle()))
.filter(b -> b.getAuthors().size() > 1)
.collect(Collectors.toList());
Stream<String> sortedTitles = library.stream().map(Book::getTitle).sorted();
Stream<Book> sortedByAuthorCount = library.stream()
.sorted(Comparator.comparing(Book::getAuthors, Comparator.comparing(List::size)));
}
@Test
public void testOptionalsAndMatchers() throws Exception {
// allMatch noneMatch anyMatch
boolean withinHeight = library.stream().filter(b -> b.getTopic() == Topic.HISTORY)
.mapToDouble(Book::getHeight).allMatch(i -> i < 19);
// findAny findFirst
Optional<Book> anyBook = library.stream().filter(b -> b.getAuthors().contains("Herman Melville")).findAny();
BufferedReader br = new BufferedReader(new FileReader("mastering.txt"));
Optional<String> line = br.lines().filter(s -> s.contains("findFirst")).findFirst();
// optional
String maybe = Optional.of("something").orElse("nothing");
String maybe2 = Optional.<String>empty().orElseGet(() -> "nothing");
}
@Test
public void testBasicReduction() throws Exception {
// statistics
IntSummaryStatistics intSummaryStatistics = IntStream.rangeClosed(1, 10).summaryStatistics();
intSummaryStatistics.getMax();
intSummaryStatistics.getMin();
IntSummaryStatistics pageCountStatistics = library.stream()
.mapToInt(b -> IntStream.of(b.getPageCount()).sum())
.summaryStatistics();
// object reduction
Optional<Book> oldestBook = library.stream().min(Comparator.comparing(Book::getTopic));
Optional<String> firstAlphabeticalTitle = library.stream().map(Book::getTitle).min(Comparator.naturalOrder());
// Comparator.reverseOrder()
// collectors
Set<String> titles = library.stream()
.map(Book::getTitle)
.collect(Collectors.toSet());
Map<String, Year> titleToPubDate = library.stream().collect(Collectors.toMap(Book::getTitle, Book::getYear)); // IllegalStateException on duplicate
}
@Test
public void testCollectors() throws Exception {
Map<Topic, List<Book>> booksByTopic = library.stream()
.collect(Collectors.groupingBy(Book::getTopic));
Map<String, Year> titleByLastPubDate = library.stream()
.collect(Collectors.toMap(Book::getTitle, Book::getYear, (x, y) -> x.isAfter(y) ? x : y));
Map<String, Year> titleToLastPubDateSorted = library.stream()
.collect(Collectors.toMap(Book::getTitle,
Book::getYear,
BinaryOperator.maxBy(Comparator.naturalOrder()),
TreeMap::new));
Map<Boolean, List<Book>> fictionNonFiction = library.stream()
.collect(Collectors.partitioningBy(b -> b.getTopic() == Topic.FICTION));
Map<Topic, Optional<Book>> bookWithMostAuthorsForEachTopic = library.stream()
.collect(Collectors.groupingBy(Book::getTopic,
Collectors.maxBy(Comparator.comparing(b -> b.getAuthors().size()))));
Map<Topic, Integer> volumeCountByTopic = library.stream()
.collect(Collectors.groupingBy(Book::getTopic, Collectors.summingInt(b -> b.getPageCount().length)));
Optional<Topic> mostPopularTopic = library.stream()
.collect(Collectors.groupingBy(Book::getTopic, Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue()) //.max(Comparator.comparing(Map.Entry::getValue))
.map(Map.Entry::getKey);
Map<Topic, String> concatTitlesByTopic = library.stream()
.collect(Collectors.groupingBy(Book::getTopic, Collectors.mapping(Book::getTitle, Collectors.joining(","))));
String concatTitles = library.stream().map(Book::getTitle).collect(Collectors.joining(", "));
List<String> authorsForBooks = library.stream()
.map(b -> b.getAuthors().stream().collect(Collectors.joining(", ", "'" + b.getTitle() + "': ", "")))//'Compilers: Principles, Techniques and Tools': Aho, Lam, Li
.collect(Collectors.toList());
}
}
@Data
@AllArgsConstructor
class Book {
private String title;
private List<String> authors;
private int[] pageCount;
private Year year;
private double height;
private Topic topic;
}
enum Topic {HISTORY, COMPUTING, FICTION, MEDICINE}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment