Skip to content

Instantly share code, notes, and snippets.

@rdehuyss
Last active August 29, 2015 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdehuyss/cdb257afa93062e8ae64 to your computer and use it in GitHub Desktop.
Save rdehuyss/cdb257afa93062e8ae64 to your computer and use it in GitHub Desktop.
Java 8 Reading Group
import org.junit.Test;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static org.fest.assertions.api.Assertions.assertThat;
public class Chapter1And2TestBackup {
private List<Collegue> collegues = Arrays.asList(
new Collegue("Ben", 35, "Axa"),
new Collegue("Jan", 30, "Mobile"),
new Collegue("Jeroen", 26, "Telcom"),
new Collegue("Niki", 23, "Telcom"),
new Collegue("Ovidiu", 30, "Telcom"),
new Collegue("Rob", 28, "Telcom"),
new Collegue("Bart", 34, "Mobile"),
new Collegue("Jorge", 34, "Telcom"),
new Collegue("Jeroen", 33, "Telcom"),
new Collegue("Georgian", 29, "Telcom")
);
@Test
public void filterCollegues_AllThatWorkForMobile() {
List<Collegue> mobileCollegues = collegues.stream()
.filter(collegue -> collegue.getDivision().equals("Mobile"))
.collect(Collectors.toList());
assertThat(mobileCollegues).hasSize(2);
}
@Test
public void filterCollegues_usingFilterTheOldestAgeInTelcom() {
OptionalInt oldestAge = collegues.stream()
.filter(collegue -> collegue.getDivision().equals("Telcom"))
.mapToInt(collegue -> collegue.getAge())
.max();
assertThat(oldestAge.getAsInt()).isEqualTo(34);
}
@Test
public void filterCollegues_usingReduceTheOldestAgeInTelcom() {
Collegue oldestCollegue = collegues.stream()
.filter(collegue -> collegue.getDivision().equals("Telcom"))
.reduce((collegue1, collegue2) -> collegue1.getAge() >= collegue2.getAge() ? collegue1 : collegue2)
.get();
assertThat(oldestCollegue.getName()).isEqualTo("Jorge");
}
@Test
public void filterCollegues_usingMaxTheOldestCollegueInTelcom() {
Collegue oldestCollegue = collegues.stream()
.filter(collegue -> collegue.getDivision().equals("Telcom"))
.max((collegue1, collegue2) -> collegue1.getAge() - collegue2.getAge())
.get();
assertThat(oldestCollegue.getName()).isEqualTo("Jorge");
}
@Test
public void filterCollegues_TheOldestCollegueInTelcomReuseLambda() {
Collegue oldestCollegue = collegues.stream()
.filter(inTelcom)
.max((collegue1, collegue2) -> collegue1.getAge() - collegue2.getAge())
.get();
assertThat(oldestCollegue.getName()).isEqualTo("Jorge");
}
@Test
public void filterCollegues_TheOldestCollegueInTelcomReuseParameterizedStaticLambda() {
Collegue oldestCollegue = collegues.stream()
.filter(inDivision("Telcom"))
.max((collegue1, collegue2) -> collegue1.getAge() - collegue2.getAge())
.get();
assertThat(oldestCollegue.getName()).isEqualTo("Jorge");
}
@Test
public void filterCollegues_TheOldestCollegueInTelcomReuseParameterizedNonStaticLambda() {
Collegue oldestCollegue = collegues.stream()
.filter(inDivisionNonStatic.apply("Telcom"))
.max((collegue1, collegue2) -> collegue1.getAge() - collegue2.getAge())
.get();
assertThat(oldestCollegue.getName()).isEqualTo("Jorge");
}
@Test
public void filterCollegues_WhichNameExistsMost() {
Optional<List<Collegue>> oldestCollegue = collegues.stream()
.collect(Collectors.groupingBy(collegue -> collegue.getName()))
.values().stream()
.max((list1, list2) -> list1.size() - list2.size());
assertThat(oldestCollegue.get().get(0).getName()).isEqualTo("Jeroen");
}
@Test
public void sortColleguesByAgeAndPrintTheirNameAndAge() {
collegues.stream()
.sorted(byAge)
.forEach(collegue -> System.out.println(collegue.getName() + " " + collegue.getAge()));
}
Comparator<Collegue> byAge = Comparator.comparing(Collegue::getAge);
Predicate<Collegue> inTelcom = collegue -> collegue.getDivision().equals("Telcom");
public static Predicate<Collegue> inDivision(final String division) {
return collegue -> collegue.getDivision().equals(division);
}
final Function<String, Predicate<Collegue>> inDivisionNonStatic = (String division) -> (Collegue collegue) -> collegue.getDivision().equals(division);
}
import org.junit.Test;
import java.io.IOException;
import java.nio.file.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.lang.Math.round;
import static java.nio.file.StandardWatchEventKinds.*;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
import static org.fest.assertions.api.Assertions.assertThat;
public class Chapter3And4TestBackup {
private List<Collegue> collegues = Arrays.asList(
new Collegue("Ben", 35, "Axa"),
new Collegue("Jan", 30, "Mobile"),
new Collegue("Jeroen", 26, "Telcom"),
new Collegue("Niki", 23, "Telcom"),
new Collegue("Ovidiu", 30, "Telcom"),
new Collegue("Rob", 28, "Telcom"),
new Collegue("Bart", 34, "Mobile"),
new Collegue("Jorge", 34, "Telcom"),
new Collegue("Jeroen", 33, "Telcom"),
new Collegue("Georgian", 29, "Telcom"),
new Collegue("Alexandru", 30, "Telcom"),
new Collegue("Emilian", 31, "Telcom"),
new Collegue("Monica", 29, "Telcom"),
new Collegue("Edward", 29, "Telcom"),
new Collegue("Radu", 33, "Telcom")
);
@Test
public void recap_filterCollegues_usingMaxTheOldestCollegueInTelcom() {
Collegue oldestCollegue = collegues.stream()
.filter(collegue -> collegue.getDivision().equals("Telcom"))
.max((collegue1, collegue2) -> collegue1.getAge() - collegue2.getAge())
.get();
assertThat(oldestCollegue.getName()).isEqualTo("Jorge");
}
@Test
public void recap_filterCollegues_WhichNameExistsMost() {
Optional<List<Collegue>> oldestCollegue = collegues.stream()
.collect(Collectors.groupingBy(Collegue::getName))
.values()
.stream()
.max(Comparator.comparingInt(List::size));
assertThat(oldestCollegue.get().get(0).getName()).isEqualTo("Jeroen");
}
@Test
public void compareAllColleguesInTelcomDivisionOnAgeDescAndNameAsc() {
List<Collegue> sortedCollegues = collegues.stream()
.filter(onDivision("Telcom"))
.sorted(comparing(onAge).reversed().thenComparing(comparing(onName)))
.collect(toList());
assertThat(sortedCollegues).hasSize(12);
assertThat(sortedCollegues.get(0).getName()).isEqualTo("Jorge");
assertThat(sortedCollegues.get(1).getName()).isEqualTo("Jeroen");
assertThat(sortedCollegues.get(2).getName()).isEqualTo("Radu");
assertThat(sortedCollegues.get(3).getName()).isEqualTo("Emilian");
assertThat(sortedCollegues.get(4).getName()).isEqualTo("Alexandru");
assertThat(sortedCollegues.get(5).getName()).isEqualTo("Ovidiu");
assertThat(sortedCollegues.get(6).getName()).isEqualTo("Edward");
assertThat(sortedCollegues.get(7).getName()).isEqualTo("Georgian");
assertThat(sortedCollegues.get(8).getName()).isEqualTo("Monica");
assertThat(sortedCollegues.get(9).getName()).isEqualTo("Rob");
assertThat(sortedCollegues.get(10).getName()).isEqualTo("Jeroen");
assertThat(sortedCollegues.get(11).getName()).isEqualTo("Niki");
}
@Test
public void countTheNumberOfAsInAllTheNames() {
int numberOfAs = collegues.stream()
.mapToInt(Chapter3And4TestBackup::countAsInAName)
.sum();
assertThat(numberOfAs).isEqualTo(9);
}
@Test
public void getAllNonBackupJavaFiles() throws IOException {
List<Path> nonBackupFiles = Files.list(Paths.get("src/main/java"))
.filter(file -> (file.toString().endsWith(".java") && !file.toString().contains("Backup")))
.collect(toList());
assertThat(nonBackupFiles).hasSize(2);
}
@Test
public void monitorFilesInSrcMainJavaAndPrintThem() throws IOException, InterruptedException {
final Path path = Paths.get("src/main/java");
WatchService watcherSvc = FileSystems.getDefault().newWatchService();
path.register(watcherSvc, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
while (true) {
WatchKey watchKey = watcherSvc.take();
watchKey.pollEvents().stream()
.forEach(event -> {System.out.println(event.context() + " " + event.kind().name()); watchKey.reset();});
}
}
@Test
public void calculateAverageAgeInMobileAndTelcom() {
double telcomAverageAge = collegues.stream()
.filter(onDivision("Telcom"))
.mapToInt(Collegue::getAge)
.average().getAsDouble();
double mobileAverageAge = collegues.stream()
.filter(onDivision("Mobile"))
.mapToInt(Collegue::getAge)
.average().getAsDouble();
assertThat(round(telcomAverageAge)).isEqualTo(30);
assertThat(round(mobileAverageAge)).isEqualTo(32);
}
@Test
public void transformAllCollegueToAYoungerVersionWithAnUppercaseNameUsingAComposedFunction() {
Function<Collegue, Collegue> transformer = nameToUppercase.compose(youngenizer);
List<Collegue> transformedCollegues = collegues.stream()
.map(transformer)
.collect(toList());
assertThat(transformedCollegues.get(0).getName()).isEqualTo("BEN");
assertThat(transformedCollegues.get(0).getAge()).isEqualTo(30);
}
Function<Collegue, Collegue> nameToUppercase = collegue -> new Collegue(collegue.getName().toUpperCase(), collegue.getAge(), collegue.getDivision());
Function<Collegue, Collegue> youngenizer = collegue -> new Collegue(collegue.getName(), collegue.getAge() - 5, collegue.getDivision());
private static int countAsInAName(Collegue collegue) {
return collegue
.getName()
.chars()
.mapToObj(convertToCharacter())
.filter(filterAllAs())
.collect(Collectors.counting()).intValue();
}
private static Predicate<? super Character> filterAllAs() {
return character -> isAnA(character);
}
private static boolean isAnA(Character character) {
return character.equals('a') || character.equals('A');
}
private static IntFunction<? extends Character> convertToCharacter() {
return ch -> Character.valueOf((char)ch);
}
private Predicate<? super Collegue> onDivision(String division) {
return collegue -> collegue.getDivision().equals(division);
}
private Function<Collegue, Integer> onAge = collegue -> collegue.getAge();
private Function<Collegue, String> onName = collegue -> collegue.getName();
}
import org.junit.Test;
import support.ContentSaver;
import support.ContentSaverBackup;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import static org.apache.commons.io.FileUtils.readFileToString;
import static support.CustomAssertions.assertThat;
public class Chapter5Test {
@Test
public void noAutoClose_getGoogleContentViaURLAndSaveToFile() throws IOException {
URL url = new URL("https://www.google.com");
URLConnection con = url.openConnection();
Reader r = new InputStreamReader(con.getInputStream(), "UTF-8");
StringBuilder buf = new StringBuilder();
for (int i = 0; i < 1000; i++) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
}
String str = buf.toString();
r.close();
File file = new File("./google-content.html");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bf = new BufferedWriter(fileWriter);
bf.write(str);
bf.close();
assertThat(readFileToString(file)).isNotEmpty();
}
@Test
public void noAutoCloseViaContentSaver_getGoogleContentViaURLAndSaveToFile() throws IOException {
File file = new File("./google-content.html");
ContentSaverBackup contentSaverBackup = new ContentSaverBackup(file);
contentSaverBackup.loadContent("https://www.google.com");
contentSaverBackup.close();
assertThat(readFileToString(file)).isNotEmpty();
}
@Test
public void autoCloseViaContentSaver_getGoogleContentViaURLAndSaveToFile() throws IOException {
File file = new File("./google-content.html");
try(final ContentSaverBackup contentSaverBackup = new ContentSaverBackup(file)){
contentSaverBackup.loadContent("https://www.google.com");
}
assertThat(readFileToString(file))
.isNotEmpty()
.contains("/images/google_favicon_128.png");
}
@Test
public void throwableAssert() {
assertThat(() -> doThrowAnException())
.throwsExceptionOfType(RuntimeException.class)
.throwsExceptionWithMessage("boe");
}
public void doThrowAnException() {
throw new RuntimeException("boe");
}
}
package support;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import static org.fest.assertions.api.Assertions.assertThat;
public class ContentSaverBackup implements AutoCloseable {
private Reader r;
private final BufferedWriter bf;
public ContentSaverBackup(File file) throws IOException {
FileWriter fileWriter = new FileWriter(file);
bf = new BufferedWriter(fileWriter);
}
public void loadContent(String toLoad) throws IOException {
URL url = new URL(toLoad);
URLConnection con = url.openConnection();
r = new InputStreamReader(con.getInputStream(), "UTF-8");
StringBuilder buf = new StringBuilder();
for(int i = 0; i < 1000; i++) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
}
String str = buf.toString();
bf.write(str);
}
@Override
public void close() {
try {
r.close();
bf.close();
} catch (IOException e) {
// do we care?
}
}
}
package support;
import org.fest.assertions.api.Assertions;
public class CustomAssertions extends Assertions {
public static ThrowableAssertions assertThat(Runnable actual) {
return new ThrowableAssertions(actual);
}
}
package support;
import org.fest.assertions.api.AbstractAssert;
import org.fest.assertions.api.Assertions;
public class ThrowableAssertions extends AbstractAssert<ThrowableAssertions, Runnable> {
protected ThrowableAssertions(Runnable actual) {
super(actual, ThrowableAssertions.class);
}
public ThrowableAssertions throwsExceptionOfType(Class<? extends Exception> clazz) {
try {
actual.run();
} catch (Throwable e) {
Assertions.assertThat(e).isInstanceOf(clazz);
}
return this;
}
public ThrowableAssertions throwsExceptionWithMessage(String boe) {
try {
actual.run();
} catch (Throwable e) {
Assertions.assertThat(e).hasMessage(boe);
}
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment