Merge pull request #8029 from catalin-burcea/BAEL-16647
[BAEL-16647] Split or move java-streams module
This commit is contained in:
6
core-java-modules/core-java-9-streams/README.md
Normal file
6
core-java-modules/core-java-9-streams/README.md
Normal file
@@ -0,0 +1,6 @@
|
||||
## Core Java 9 streams
|
||||
|
||||
This module contains articles about Java 9 streams
|
||||
|
||||
### Relevant Articles:
|
||||
- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach)
|
||||
31
core-java-modules/core-java-9-streams/pom.xml
Normal file
31
core-java-modules/core-java-9-streams/pom.xml
Normal file
@@ -0,0 +1,31 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-9-streams</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-9-streams</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-9-streams</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.streams.breakforeach;
|
||||
|
||||
import java.util.Spliterator;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class CustomForEach {
|
||||
|
||||
public static class Breaker {
|
||||
private boolean shouldBreak = false;
|
||||
|
||||
public void stop() {
|
||||
shouldBreak = true;
|
||||
}
|
||||
|
||||
boolean get() {
|
||||
return shouldBreak;
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> void forEach(Stream<T> stream, BiConsumer<T, Breaker> consumer) {
|
||||
Spliterator<T> spliterator = stream.spliterator();
|
||||
boolean hadNext = true;
|
||||
Breaker breaker = new Breaker();
|
||||
|
||||
while (hadNext && !breaker.get()) {
|
||||
hadNext = spliterator.tryAdvance(elem -> {
|
||||
consumer.accept(elem, breaker);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.streams.breakforeach;
|
||||
|
||||
import java.util.Spliterator;
|
||||
import java.util.Spliterators;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class CustomSpliterator<T> extends Spliterators.AbstractSpliterator<T> {
|
||||
|
||||
private Spliterator<T> splitr;
|
||||
private Predicate<T> predicate;
|
||||
private boolean isMatched = true;
|
||||
|
||||
public CustomSpliterator(Spliterator<T> splitr, Predicate<T> predicate) {
|
||||
super(splitr.estimateSize(), 0);
|
||||
this.splitr = splitr;
|
||||
this.predicate = predicate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean tryAdvance(Consumer<? super T> consumer) {
|
||||
boolean hadNext = splitr.tryAdvance(elem -> {
|
||||
if (predicate.test(elem) && isMatched) {
|
||||
consumer.accept(elem);
|
||||
} else {
|
||||
isMatched = false;
|
||||
}
|
||||
});
|
||||
return hadNext && isMatched;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.streams.breakforeach;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
public class CustomTakeWhile {
|
||||
|
||||
public static <T> Stream<T> takeWhile(Stream<T> stream, Predicate<T> predicate) {
|
||||
CustomSpliterator<T> customSpliterator = new CustomSpliterator<>(stream.spliterator(), predicate);
|
||||
return StreamSupport.stream(customSpliterator, false);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.streams.breakforeach;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
|
||||
public class TakeWhileExample {
|
||||
|
||||
public static void takeWhileJava9() {
|
||||
Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck")
|
||||
.takeWhile(n -> n.length() % 2 != 0)
|
||||
.forEach(System.out::println); // cat, dog
|
||||
}
|
||||
|
||||
public static void plainForLoopWithBreak() {
|
||||
List<String> list = asList("cat", "dog", "elephant", "fox", "rabbit", "duck");
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
String item = list.get(i);
|
||||
if (item.length() % 2 == 0) {
|
||||
break;
|
||||
}
|
||||
System.out.println(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.streams.breakforeach;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class BreakFromStreamForEachUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCustomTakeWhileIsCalled_ThenCorrectItemsAreReturned() {
|
||||
Stream<String> initialStream = Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck");
|
||||
|
||||
List<String> result = CustomTakeWhile.takeWhile(initialStream, x -> x.length() % 2 != 0)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertEquals(asList("cat", "dog"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomForEachIsCalled_ThenCorrectItemsAreReturned() {
|
||||
Stream<String> initialStream = Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck");
|
||||
List<String> result = new ArrayList<>();
|
||||
|
||||
CustomForEach.forEach(initialStream, (elem, breaker) -> {
|
||||
if (elem.length() % 2 == 0) {
|
||||
breaker.stop();
|
||||
} else {
|
||||
result.add(elem);
|
||||
}
|
||||
});
|
||||
|
||||
assertEquals(asList("cat", "dog"), result);
|
||||
}
|
||||
|
||||
}
|
||||
16
core-java-modules/core-java-streams-2/README.md
Normal file
16
core-java-modules/core-java-streams-2/README.md
Normal file
@@ -0,0 +1,16 @@
|
||||
## Core Java streams
|
||||
|
||||
This module contains articles about the Stream API in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams)
|
||||
- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction)
|
||||
- [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany)
|
||||
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)
|
||||
- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert)
|
||||
- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api)
|
||||
- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams)
|
||||
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
|
||||
- [How to Add a Single Element to a Stream](https://www.baeldung.com/java-stream-append-prepend)
|
||||
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
||||
- More articles: [[<-- prev>]](/../core-java-streams) [[next -->]](/../core-java-streams-3)
|
||||
53
core-java-modules/core-java-streams-2/pom.xml
Normal file
53
core-java-modules/core-java-streams-2/pom.xml
Normal file
@@ -0,0 +1,53 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-streams-2</artifactId>
|
||||
<version>1.0</version>
|
||||
<name>core-java-streams-2</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
<type>jar</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.reduce.application;
|
||||
|
||||
import com.baeldung.reduce.entities.User;
|
||||
import com.baeldung.reduce.utilities.NumberUtils;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
||||
System.out.println(result1);
|
||||
|
||||
int result2 = numbers.stream().reduce(0, Integer::sum);
|
||||
System.out.println(result2);
|
||||
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
||||
System.out.println(result3);
|
||||
|
||||
String result4 = letters.stream().reduce("", String::concat);
|
||||
System.out.println(result4);
|
||||
|
||||
String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
||||
System.out.println(result5);
|
||||
|
||||
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
||||
int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
System.out.println(result6);
|
||||
|
||||
String result7 = letters.parallelStream().reduce("", String::concat);
|
||||
System.out.println(result7);
|
||||
|
||||
int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
System.out.println(result8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.reduce.benchmarks;
|
||||
|
||||
import com.baeldung.reduce.entities.User;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
@State(Scope.Thread)
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public class JMHStreamReduceBenchMark {
|
||||
|
||||
private final List<User> userList = createUsers();
|
||||
|
||||
public static void main(String[] args) throws RunnerException {
|
||||
|
||||
Options options = new OptionsBuilder()
|
||||
.include(JMHStreamReduceBenchMark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true).shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
|
||||
private List<User> createUsers() {
|
||||
List<User> users = new ArrayList<>();
|
||||
for (int i = 0; i <= 1000000; i++) {
|
||||
users.add(new User("John" + i, i));
|
||||
}
|
||||
return users;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Integer executeReduceOnParallelizedStream() {
|
||||
return this.userList
|
||||
.parallelStream()
|
||||
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Integer executeReduceOnSequentialStream() {
|
||||
return this.userList
|
||||
.stream()
|
||||
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.reduce.entities;
|
||||
|
||||
public class User {
|
||||
|
||||
private final String name;
|
||||
private final int age;
|
||||
|
||||
public User(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "name=" + name + ", age=" + age + '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.reduce.utilities;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public abstract class NumberUtils {
|
||||
|
||||
private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName());
|
||||
|
||||
public static int divideListElements(List<Integer> values, Integer divider) {
|
||||
return values.stream()
|
||||
.reduce(0, (a, b) -> {
|
||||
try {
|
||||
return a / divider + b / divider;
|
||||
} catch (ArithmeticException e) {
|
||||
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
public static int divideListElementsWithExtractedTryCatchBlock(List<Integer> values, int divider) {
|
||||
return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider));
|
||||
}
|
||||
|
||||
public static int divideListElementsWithApplyFunctionMethod(List<Integer> values, int divider) {
|
||||
BiFunction<Integer, Integer, Integer> division = (a, b) -> a / b;
|
||||
return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider));
|
||||
}
|
||||
|
||||
private static int divide(int value, int factor) {
|
||||
int result = 0;
|
||||
try {
|
||||
result = value / factor;
|
||||
} catch (ArithmeticException e) {
|
||||
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int applyFunction(BiFunction<Integer, Integer, Integer> function, int a, int b) {
|
||||
try {
|
||||
return function.apply(a, b);
|
||||
}
|
||||
catch(Exception e) {
|
||||
LOGGER.log(Level.INFO, "Exception thrown!");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collector;
|
||||
|
||||
public class MyImmutableListCollector {
|
||||
|
||||
public static <T, A extends List<T>> Collector<T, A, List<T>> toImmutableList(Supplier<A> supplier) {
|
||||
return Collector.of(supplier, List::add, (left, right) -> {
|
||||
left.addAll(right);
|
||||
return left;
|
||||
}, Collections::unmodifiableList);
|
||||
}
|
||||
|
||||
public static <T> Collector<T, List<T>, List<T>> toImmutableList() {
|
||||
return toImmutableList(ArrayList::new);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.convert.intstreams;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class IntStreamsConversionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void intStreamToArray() {
|
||||
int[] first50EvenNumbers = IntStream.iterate(0, i -> i + 2)
|
||||
.limit(50)
|
||||
.toArray();
|
||||
|
||||
assertThat(first50EvenNumbers).hasSize(50);
|
||||
assertThat(first50EvenNumbers[2]).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void intStreamToList() {
|
||||
List<Integer> first50IntegerNumbers = IntStream.range(0, 50)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(first50IntegerNumbers).hasSize(50);
|
||||
assertThat(first50IntegerNumbers.get(2)).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void intStreamToString() {
|
||||
String first3numbers = IntStream.of(0, 1, 2)
|
||||
.mapToObj(String::valueOf)
|
||||
.collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
assertThat(first3numbers).isEqualTo("[0, 1, 2]");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.reduce;
|
||||
|
||||
import com.baeldung.reduce.entities.User;
|
||||
import com.baeldung.reduce.utilities.NumberUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StreamReduceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
||||
assertThat(result).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
int result = numbers.stream().reduce(0, Integer::sum);
|
||||
assertThat(result).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
||||
assertThat(result).isEqualTo("abcde");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.stream().reduce("", String::concat);
|
||||
assertThat(result).isEqualTo("abcde");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
||||
assertThat(result).isEqualTo("ABCDE");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
|
||||
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
||||
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
assertThat(result).isEqualTo(65);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithParallelStream_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.parallelStream().reduce("", String::concat);
|
||||
assertThat(result).isEqualTo("abcde");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class Detail {
|
||||
|
||||
private static final List<String> PARTS = Arrays.asList("turbine", "pump");
|
||||
|
||||
public List<String> getParts() {
|
||||
return PARTS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.hamcrest.Matchers.anyOf;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class Java8FindAnyFindFirstUnitTest {
|
||||
|
||||
@Test
|
||||
public void createStream_whenFindAnyResultIsPresent_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("A", "B", "C", "D");
|
||||
|
||||
Optional<String> result = list.stream().findAny();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertThat(result.get(), anyOf(is("A"), is("B"), is("C"), is("D")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception {
|
||||
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Optional<Integer> result = list.stream().parallel().filter(num -> num < 4).findAny();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertThat(result.get(), anyOf(is(1), is(2), is(3)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStream_whenFindFirstResultIsPresent_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("A", "B", "C", "D");
|
||||
|
||||
Optional<String> result = list.stream().findFirst();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertThat(result.get(), is("A"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.*;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8StreamApiUnitTest {
|
||||
|
||||
private long counter;
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(Java8StreamApiUnitTest.class);
|
||||
|
||||
private List<Product> productList;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
productList = Arrays.asList(new Product(23, "potatoes"), new Product(14, "orange"), new Product(13, "lemon"), new Product(23, "bread"), new Product(13, "sugar"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
long size = list.stream().skip(1).map(element -> element.substring(0, 3)).count();
|
||||
assertEquals(list.size() - 1, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
|
||||
counter = 0;
|
||||
long sizeFirst = list.stream().skip(2).map(element -> {
|
||||
wasCalled();
|
||||
return element.substring(0, 3);
|
||||
}).count();
|
||||
assertEquals(1, counter);
|
||||
|
||||
counter = 0;
|
||||
long sizeSecond = list.stream().map(element -> {
|
||||
wasCalled();
|
||||
return element.substring(0, 3);
|
||||
}).skip(2).count();
|
||||
assertEquals(3, counter);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createEmptyStream_whenEmpty_thenCorrect() {
|
||||
|
||||
Stream<String> streamEmpty = Stream.empty();
|
||||
assertEquals(0, streamEmpty.count());
|
||||
|
||||
List<String> names = Collections.emptyList();
|
||||
Stream<String> streamOf = Product.streamOf(names);
|
||||
assertTrue(streamOf.count() == 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createStream_whenCreated_thenCorrect() {
|
||||
|
||||
Collection<String> collection = Arrays.asList("a", "b", "c");
|
||||
Stream<String> streamOfCollection = collection.stream();
|
||||
assertEquals(3, streamOfCollection.count());
|
||||
|
||||
Stream<String> streamOfArray = Stream.of("a", "b", "c");
|
||||
assertEquals(3, streamOfArray.count());
|
||||
|
||||
String[] arr = new String[] { "a", "b", "c" };
|
||||
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3);
|
||||
assertEquals(2, streamOfArrayPart.count());
|
||||
|
||||
IntStream intStream = IntStream.range(1, 3);
|
||||
LongStream longStream = LongStream.rangeClosed(1, 3);
|
||||
Random random = new Random();
|
||||
DoubleStream doubleStream = random.doubles(3);
|
||||
assertEquals(2, intStream.count());
|
||||
assertEquals(3, longStream.count());
|
||||
assertEquals(3, doubleStream.count());
|
||||
|
||||
IntStream streamOfChars = "abc".chars();
|
||||
IntStream str = "".chars();
|
||||
assertEquals(3, streamOfChars.count());
|
||||
|
||||
Stream<String> streamOfString = Pattern.compile(", ").splitAsStream("a, b, c");
|
||||
assertEquals("a", streamOfString.findFirst().get());
|
||||
|
||||
Path path = getPath();
|
||||
Stream<String> streamOfStrings = null;
|
||||
try {
|
||||
streamOfStrings = Files.lines(path, Charset.forName("UTF-8"));
|
||||
} catch (IOException e) {
|
||||
log.error("Error creating streams from paths {}", path, e.getMessage(), e);
|
||||
}
|
||||
assertEquals("a", streamOfStrings.findFirst().get());
|
||||
|
||||
Stream<String> streamBuilder = Stream.<String> builder().add("a").add("b").add("c").build();
|
||||
assertEquals(3, streamBuilder.count());
|
||||
|
||||
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
|
||||
assertEquals(10, streamGenerated.count());
|
||||
|
||||
Stream<Integer> streamIterated = Stream.iterate(40, n -> n + 2).limit(20);
|
||||
assertTrue(40 <= streamIterated.findAny().get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
|
||||
|
||||
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
|
||||
Optional<String> stream = list.stream().filter(element -> {
|
||||
log.info("filter() was called");
|
||||
return element.contains("2");
|
||||
}).map(element -> {
|
||||
log.info("map() was called");
|
||||
return element.toUpperCase();
|
||||
}).findFirst();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void reduce_whenExpected_thenCorrect() {
|
||||
|
||||
OptionalInt reduced = IntStream.range(1, 4).reduce((a, b) -> a + b);
|
||||
assertEquals(6, reduced.getAsInt());
|
||||
|
||||
int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
|
||||
assertEquals(16, reducedTwoParams);
|
||||
|
||||
int reducedThreeParams = Stream.of(1, 2, 3).reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||
log.info("combiner was called");
|
||||
return a + b;
|
||||
});
|
||||
assertEquals(16, reducedThreeParams);
|
||||
|
||||
int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream().reduce(10, (a, b) -> a + b, (a, b) -> {
|
||||
log.info("combiner was called");
|
||||
return a + b;
|
||||
});
|
||||
assertEquals(36, reducedThreeParamsParallel);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void collecting_whenAsExpected_thenCorrect() {
|
||||
|
||||
List<String> collectorCollection = productList.stream().map(Product::getName).collect(Collectors.toList());
|
||||
|
||||
assertTrue(collectorCollection instanceof List);
|
||||
assertEquals(5, collectorCollection.size());
|
||||
|
||||
String listToString = productList.stream().map(Product::getName).collect(Collectors.joining(", ", "[", "]"));
|
||||
|
||||
assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
|
||||
|
||||
double averagePrice = productList.stream().collect(Collectors.averagingInt(Product::getPrice));
|
||||
assertTrue(17.2 == averagePrice);
|
||||
|
||||
int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
|
||||
assertEquals(86, summingPrice);
|
||||
|
||||
IntSummaryStatistics statistics = productList.stream().collect(Collectors.summarizingInt(Product::getPrice));
|
||||
assertEquals(23, statistics.getMax());
|
||||
|
||||
Map<Integer, List<Product>> collectorMapOfLists = productList.stream().collect(Collectors.groupingBy(Product::getPrice));
|
||||
assertEquals(3, collectorMapOfLists.keySet().size());
|
||||
|
||||
Map<Boolean, List<Product>> mapPartioned = productList.stream().collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
|
||||
assertEquals(2, mapPartioned.keySet().size());
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void collect_whenThrows_thenCorrect() {
|
||||
Set<Product> unmodifiableSet = productList.stream().collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
|
||||
unmodifiableSet.add(new Product(4, "tea"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
|
||||
Collector<Product, ?, LinkedList<Product>> toLinkedList = Collector.of(LinkedList::new, LinkedList::add, (first, second) -> {
|
||||
first.addAll(second);
|
||||
return first;
|
||||
});
|
||||
|
||||
LinkedList<Product> linkedListOfPersons = productList.stream().collect(toLinkedList);
|
||||
assertTrue(linkedListOfPersons.containsAll(productList));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallelStream_whenWorks_thenCorrect() {
|
||||
Stream<Product> streamOfCollection = productList.parallelStream();
|
||||
boolean isParallel = streamOfCollection.isParallel();
|
||||
boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12).anyMatch(price -> price > 200);
|
||||
assertTrue(isParallel && haveBigPrice);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallel_whenIsParallel_thenCorrect() {
|
||||
IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||
boolean isParallel = intStreamParallel.isParallel();
|
||||
assertTrue(isParallel);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parallel_whenIsSequential_thenCorrect() {
|
||||
IntStream intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34);
|
||||
IntStream intStreamSequential = intStreamParallel.sequential();
|
||||
boolean isParallel = intStreamParallel.isParallel();
|
||||
assertFalse(isParallel);
|
||||
}
|
||||
|
||||
private Path getPath() {
|
||||
Path path = null;
|
||||
try {
|
||||
path = Files.createTempFile(null, ".txt");
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
|
||||
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
|
||||
writer.write("a\nb\nc");
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private void wasCalled() {
|
||||
counter++;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class Java8StreamsUnitTest {
|
||||
|
||||
private List<String> list;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
list = new ArrayList<>();
|
||||
list.add("One");
|
||||
list.add("OneAndOnly");
|
||||
list.add("Derek");
|
||||
list.add("Change");
|
||||
list.add("factory");
|
||||
list.add("justBefore");
|
||||
list.add("Italy");
|
||||
list.add("Italy");
|
||||
list.add("Thursday");
|
||||
list.add("");
|
||||
list.add("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenCreating_givenDifferentSources() {
|
||||
String[] arr = new String[] { "a", "b", "c" };
|
||||
Stream<String> streamArr = Arrays.stream(arr);
|
||||
assertEquals(streamArr.count(), 3);
|
||||
|
||||
Stream<String> streamOf = Stream.of("a", "b", "c");
|
||||
assertEquals(streamOf.count(), 3);
|
||||
|
||||
long count = list.stream().distinct().count();
|
||||
assertEquals(count, 9);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationFilter_thanCorrect() {
|
||||
Stream<String> streamFilter = list.stream().filter(element -> element.isEmpty());
|
||||
assertEquals(streamFilter.count(), 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationMap_thanCorrect() {
|
||||
List<String> uris = new ArrayList<>();
|
||||
uris.add("C:\\My.txt");
|
||||
Stream<Path> streamMap = uris.stream().map(uri -> Paths.get(uri));
|
||||
assertEquals(streamMap.count(), 1);
|
||||
|
||||
List<Detail> details = new ArrayList<>();
|
||||
details.add(new Detail());
|
||||
details.add(new Detail());
|
||||
Stream<String> streamFlatMap = details.stream().flatMap(detail -> detail.getParts().stream());
|
||||
assertEquals(streamFlatMap.count(), 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamCount_whenOperationMatch_thenCorrect() {
|
||||
boolean isValid = list.stream().anyMatch(element -> element.contains("h"));
|
||||
boolean isValidOne = list.stream().allMatch(element -> element.contains("h"));
|
||||
boolean isValidTwo = list.stream().noneMatch(element -> element.contains("h"));
|
||||
assertTrue(isValid);
|
||||
assertFalse(isValidOne);
|
||||
assertFalse(isValidTwo);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamReducedValue_whenOperationReduce_thenCorrect() {
|
||||
List<Integer> integers = new ArrayList<>();
|
||||
integers.add(1);
|
||||
integers.add(1);
|
||||
integers.add(1);
|
||||
Integer reduced = integers.stream().reduce(23, (a, b) -> a + b);
|
||||
assertTrue(reduced == 26);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStreamContains_whenOperationCollect_thenCorrect() {
|
||||
List<String> resultList = list.stream().map(element -> element.toUpperCase()).collect(Collectors.toList());
|
||||
assertEquals(resultList.size(), list.size());
|
||||
assertTrue(resultList.contains(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkParallelStream_whenDoWork() {
|
||||
list.parallelStream().forEach(element -> doWork(element));
|
||||
}
|
||||
|
||||
private void doWork(String string) {
|
||||
assertTrue(true); // just imitate an amount of work
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class PeekUnitTest {
|
||||
|
||||
private StringWriter out;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
out = new StringWriter();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringStream_whenCallingPeekOnly_thenNoElementProcessed() {
|
||||
// given
|
||||
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
|
||||
|
||||
// when
|
||||
nameStream.peek(out::append);
|
||||
|
||||
// then
|
||||
assertThat(out.toString()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringStream_whenCallingForEachOnly_thenElementsProcessed() {
|
||||
// given
|
||||
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
|
||||
|
||||
// when
|
||||
nameStream.forEach(out::append);
|
||||
|
||||
// then
|
||||
assertThat(out.toString()).isEqualTo("AliceBobChuck");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringStream_whenCallingPeekAndNoopForEach_thenElementsProcessed() {
|
||||
// given
|
||||
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
|
||||
|
||||
// when
|
||||
nameStream.peek(out::append)
|
||||
.forEach(this::noop);
|
||||
|
||||
// then
|
||||
assertThat(out.toString()).isEqualTo("AliceBobChuck");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringStream_whenCallingPeekAndCollect_thenElementsProcessed() {
|
||||
// given
|
||||
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
|
||||
|
||||
// when
|
||||
nameStream.peek(out::append)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// then
|
||||
assertThat(out.toString()).isEqualTo("AliceBobChuck");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringStream_whenCallingPeekAndForEach_thenElementsProcessedTwice() {
|
||||
// given
|
||||
Stream<String> nameStream = Stream.of("Alice", "Bob", "Chuck");
|
||||
|
||||
// when
|
||||
nameStream.peek(out::append)
|
||||
.forEach(out::append);
|
||||
|
||||
// then
|
||||
assertThat(out.toString()).isEqualTo("AliceAliceBobBobChuckChuck");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStringStream_whenCallingPeek_thenElementsProcessedTwice() {
|
||||
// given
|
||||
Stream<User> userStream = Stream.of(new User("Alice"), new User("Bob"), new User("Chuck"));
|
||||
|
||||
// when
|
||||
userStream.peek(u -> u.setName(u.getName().toLowerCase()))
|
||||
.map(User::getName)
|
||||
.forEach(out::append);
|
||||
|
||||
// then
|
||||
assertThat(out.toString()).isEqualTo("alicebobchuck");
|
||||
}
|
||||
|
||||
private static class User {
|
||||
private String name;
|
||||
|
||||
public User(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void noop(String s) {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Created by Alex Vengr
|
||||
*/
|
||||
public class Product {
|
||||
|
||||
private int price;
|
||||
|
||||
private String name;
|
||||
|
||||
private boolean utilize;
|
||||
|
||||
public Product(int price, String name) {
|
||||
this(price);
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Product(int price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public Product() {
|
||||
}
|
||||
|
||||
public int getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(int price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static Stream<String> streamOf(List<String> list) {
|
||||
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamAddUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStream_whenAppendingObject_thenAppended() {
|
||||
Stream<String> anStream = Stream.of("a", "b", "c", "d", "e");
|
||||
|
||||
Stream<String> newStream = Stream.concat(anStream, Stream.of("A"));
|
||||
|
||||
List<String> resultList = newStream.collect(Collectors.toList());
|
||||
assertEquals(resultList.get(resultList.size() - 1), "A");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenPrependingObject_thenPrepended() {
|
||||
Stream<Integer> anStream = Stream.of(1, 2, 3, 4, 5);
|
||||
|
||||
Stream<Integer> newStream = Stream.concat(Stream.of(99), anStream);
|
||||
|
||||
assertEquals(newStream.findFirst()
|
||||
.get(), (Integer) 99);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenInsertingObject_thenInserted() {
|
||||
Stream<Double> anStream = Stream.of(1.1, 2.2, 3.3);
|
||||
|
||||
Stream<Double> newStream = insertInStream(anStream, 9.9, 3);
|
||||
|
||||
List<Double> resultList = newStream.collect(Collectors.toList());
|
||||
assertEquals(resultList.get(3), (Double) 9.9);
|
||||
}
|
||||
|
||||
private <T> Stream<T> insertInStream(Stream<T> stream, T elem, int index) {
|
||||
List<T> result = stream.collect(Collectors.toList());
|
||||
result.add(index, elem);
|
||||
return result.stream();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class StreamMapUnitTest {
|
||||
|
||||
private Map<String, String> books;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
books = new HashMap<>();
|
||||
books.put("978-0201633610", "Design patterns : elements of reusable object-oriented software");
|
||||
books.put("978-1617291999", "Java 8 in Action: Lambdas, Streams, and functional-style programming");
|
||||
books.put("978-0134685991", "Effective Java");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenOptionalVersionCalledForExistingTitle_thenReturnOptionalWithISBN() {
|
||||
Optional<String> optionalIsbn = books.entrySet().stream()
|
||||
.filter(e -> "Effective Java".equals(e.getValue()))
|
||||
.map(Map.Entry::getKey).findFirst();
|
||||
|
||||
assertEquals("978-0134685991", optionalIsbn.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOptionalVersionCalledForNonExistingTitle_thenReturnEmptyOptionalForISBN() {
|
||||
Optional<String> optionalIsbn = books.entrySet().stream()
|
||||
.filter(e -> "Non Existent Title".equals(e.getValue()))
|
||||
.map(Map.Entry::getKey).findFirst();
|
||||
|
||||
assertEquals(false, optionalIsbn.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMultipleResultsVersionCalledForExistingTitle_aCollectionWithMultipleValuesIsReturned() {
|
||||
books.put("978-0321356680", "Effective Java: Second Edition");
|
||||
|
||||
List<String> isbnCodes = books.entrySet().stream()
|
||||
.filter(e -> e.getValue().startsWith("Effective Java"))
|
||||
.map(Map.Entry::getKey)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(isbnCodes.contains("978-0321356680"));
|
||||
assertTrue(isbnCodes.contains("978-0134685991"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMultipleResultsVersionCalledForNonExistingTitle_aCollectionWithNoValuesIsReturned() {
|
||||
List<String> isbnCodes = books.entrySet().stream()
|
||||
.filter(e -> e.getValue().startsWith("Spring"))
|
||||
.map(Map.Entry::getKey)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertTrue(isbnCodes.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenKeysFollowingPatternReturnsAllValuesForThoseKeys() {
|
||||
List<String> titlesForKeyPattern = books.entrySet().stream()
|
||||
.filter(e -> e.getKey().startsWith("978-0"))
|
||||
.map(Map.Entry::getValue)
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(2, titlesForKeyPattern.size());
|
||||
assertTrue(titlesForKeyPattern.contains("Design patterns : elements of reusable object-oriented software"));
|
||||
assertTrue(titlesForKeyPattern.contains("Effective Java"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.streams;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static java.util.stream.Collectors.*;
|
||||
|
||||
public class StreamToImmutableUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingCollectingToImmutableSet_thenSuccess() {
|
||||
List<String> givenList = Arrays.asList("a", "b", "c");
|
||||
List<String> result = givenList.stream()
|
||||
.collect(collectingAndThen(toSet(), ImmutableList::copyOf));
|
||||
|
||||
System.out.println(result.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCollectingToUnmodifiableList_thenSuccess() {
|
||||
List<String> givenList = new ArrayList<>(Arrays.asList("a", "b", "c"));
|
||||
List<String> result = givenList.stream()
|
||||
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
|
||||
|
||||
System.out.println(result.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectToImmutableList_thenSuccess() {
|
||||
List<Integer> list = IntStream.range(0, 9)
|
||||
.boxed()
|
||||
.collect(ImmutableList.toImmutableList());
|
||||
|
||||
System.out.println(list.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectToMyImmutableListCollector_thenSuccess() {
|
||||
List<String> givenList = Arrays.asList("a", "b", "c", "d");
|
||||
List<String> result = givenList.stream()
|
||||
.collect(MyImmutableListCollector.toImmutableList());
|
||||
|
||||
System.out.println(result.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPassingSupplier_thenSuccess() {
|
||||
List<String> givenList = Arrays.asList("a", "b", "c", "d");
|
||||
List<String> result = givenList.stream()
|
||||
.collect(MyImmutableListCollector.toImmutableList(LinkedList::new));
|
||||
|
||||
System.out.println(result.getClass());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.streams.removeitem;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StreamOperateAndRemoveUnitTest {
|
||||
|
||||
private List<Item> itemList;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
|
||||
itemList = new ArrayList<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
itemList.add(new Item(i));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOf10Items_whenFilteredForQualifiedItems_thenFilteredListContains5Items() {
|
||||
|
||||
final List<Item> filteredList = itemList.stream().filter(item -> item.isQualified())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
Assert.assertEquals(5, filteredList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() {
|
||||
|
||||
final Predicate<Item> isQualified = item -> item.isQualified();
|
||||
itemList.stream().filter(isQualified).forEach(item -> item.operate());
|
||||
itemList.removeIf(isQualified);
|
||||
|
||||
Assert.assertEquals(5, itemList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveAll_thenListContains5Items() {
|
||||
|
||||
final List<Item> operatedList = new ArrayList<>();
|
||||
itemList.stream().filter(item -> item.isQualified()).forEach(item -> {
|
||||
item.operate();
|
||||
operatedList.add(item);
|
||||
});
|
||||
itemList.removeAll(operatedList);
|
||||
|
||||
Assert.assertEquals(5, itemList.size());
|
||||
}
|
||||
|
||||
class Item {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
|
||||
|
||||
private final int value;
|
||||
|
||||
public Item(final int value) {
|
||||
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public boolean isQualified() {
|
||||
|
||||
return value % 2 == 0;
|
||||
}
|
||||
|
||||
public void operate() {
|
||||
|
||||
logger.info("Even Number: " + this.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
11
core-java-modules/core-java-streams-3/README.md
Normal file
11
core-java-modules/core-java-streams-3/README.md
Normal file
@@ -0,0 +1,11 @@
|
||||
## Core Java streams
|
||||
|
||||
This module contains articles about the Stream API in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap)
|
||||
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
|
||||
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
|
||||
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
||||
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
|
||||
- More articles: [[<-- prev>]](/../core-java-streams-2)
|
||||
53
core-java-modules/core-java-streams-3/pom.xml
Normal file
53
core-java-modules/core-java-streams-3/pom.xml
Normal file
@@ -0,0 +1,53 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-streams-3</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-streams-3</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-streams-3</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<!-- plugins -->
|
||||
<maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.forEach;
|
||||
package com.baeldung.streams.forEach;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.streams.primitivestreams;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
class PrimitiveStreams {
|
||||
|
||||
int min(int[] integers) {
|
||||
return Arrays.stream(integers).min().getAsInt();
|
||||
}
|
||||
|
||||
int max(int... integers) {
|
||||
return IntStream.of(integers).max().getAsInt();
|
||||
}
|
||||
|
||||
int sum(int... integers) {
|
||||
return IntStream.of(integers).sum();
|
||||
}
|
||||
|
||||
double avg(int... integers) {
|
||||
return IntStream.of(integers).average().getAsDouble();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.collectors;
|
||||
package com.baeldung.streams.collectors;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.stream.conditional;
|
||||
package com.baeldung.streams.conditional;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.baeldung.streams.primitivestreams;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PrimitiveStreamsUnitTest {
|
||||
|
||||
private PrimitiveStreams streams = new PrimitiveStreams();
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() {
|
||||
int[] integers = new int[] { 20, 98, 12, 7, 35 };
|
||||
int min = streams.min(integers); // returns 7
|
||||
|
||||
assertEquals(7, min);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenMaxIsCalledThenCorrectMaxIsReturned() {
|
||||
int max = streams.max(20, 98, 12, 7, 35);
|
||||
|
||||
assertEquals(98, max);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenSumIsCalledThenCorrectSumIsReturned() {
|
||||
int sum = streams.sum(20, 98, 12, 7, 35);
|
||||
|
||||
assertEquals(172, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenAvgIsCalledThenCorrectAvgIsReturned() {
|
||||
double avg = streams.avg(20, 98, 12, 7, 35);
|
||||
|
||||
assertTrue(34.4 == avg);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenARangeOfIntegersWhenIntStreamSumIsCalledThenCorrectSumIsReturned() {
|
||||
int sum = IntStream.range(1, 10).sum();
|
||||
|
||||
assertEquals(45, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenARangeClosedOfIntegersWhenIntStreamSumIsCalledThenCorrectSumIsReturned() {
|
||||
int sum = IntStream.rangeClosed(1, 10).sum();
|
||||
|
||||
assertEquals(55, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenARangeWhenForEachIsCalledThenTheIndicesWillBePrinted() {
|
||||
IntStream.rangeClosed(1, 5).parallel().forEach(System.out::println);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() {
|
||||
|
||||
int sum = Stream.of(33, 45).mapToInt(i -> i).sum();
|
||||
|
||||
assertEquals(78, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIntStreamThenGetTheEvenIntegers() {
|
||||
List<Integer> evenInts = IntStream.rangeClosed(1, 10).filter(i -> i % 2 == 0).boxed().collect(Collectors.toList());
|
||||
|
||||
List<Integer> expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList());
|
||||
|
||||
assertEquals(expected, evenInts);
|
||||
}
|
||||
|
||||
class Person {
|
||||
private int age;
|
||||
|
||||
Person(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
int getAge() {
|
||||
return age;
|
||||
}
|
||||
}
|
||||
}
|
||||
26
core-java-modules/core-java-streams/.gitignore
vendored
Normal file
26
core-java-modules/core-java-streams/.gitignore
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
||||
@@ -1,9 +1,16 @@
|
||||
=========
|
||||
## Core Java streams
|
||||
|
||||
## Core Java 8 Cookbooks and Examples
|
||||
This module contains articles about the Stream API in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap)
|
||||
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
|
||||
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
|
||||
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
||||
- [Java 8 and Infinite Streams](https://www.baeldung.com/java-inifinite-streams)
|
||||
- [How to Get the Last Element of a Stream in Java?](https://www.baeldung.com/java-stream-last-element)
|
||||
- [“Stream has already been operated upon or closed” Exception in Java](https://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
|
||||
- [Iterable to Stream in Java](https://www.baeldung.com/java-iterable-to-stream)
|
||||
- [How to Iterate Over a Stream With Indices](https://www.baeldung.com/java-stream-indices)
|
||||
- [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering)
|
||||
- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack)
|
||||
- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda)
|
||||
- [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count)
|
||||
- [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum)
|
||||
- More articles: [[next -->]](/../core-java-streams-2)
|
||||
@@ -14,6 +14,34 @@
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh-core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh-generator.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
@@ -21,6 +49,36 @@
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.codepoetics</groupId>
|
||||
<artifactId>protonpack</artifactId>
|
||||
<version>${protonpack.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>${streamex.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjrt</artifactId>
|
||||
<version>${asspectj.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjweaver</artifactId>
|
||||
<version>${asspectj.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>pl.touk</groupId>
|
||||
<artifactId>throwing-function</artifactId>
|
||||
<version>${throwing-function.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -31,10 +89,33 @@
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
<compilerArgument>-parameters</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
<protonpack.version>1.15</protonpack.version>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
<joda.version>2.10</joda.version>
|
||||
<throwing-function.version>1.3</throwing-function.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<assertj.version>3.11.1</assertj.version>
|
||||
<asspectj.version>1.8.9</asspectj.version>
|
||||
<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class InfiniteStreams {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(InfiniteStreams.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
doWhileOldWay();
|
||||
|
||||
doWhileStreamWay();
|
||||
|
||||
}
|
||||
|
||||
private static void doWhileOldWay() {
|
||||
|
||||
int i = 0;
|
||||
while (i < 10) {
|
||||
LOG.debug("{}", i);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
private static void doWhileStreamWay() {
|
||||
Stream<Integer> integers = Stream.iterate(0, i -> i + 1);
|
||||
integers.limit(10).forEach(System.out::println);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class StreamApi {
|
||||
|
||||
public static String getLastElementUsingReduce(List<String> valueList) {
|
||||
Stream<String> stream = valueList.stream();
|
||||
return stream.reduce((first, second) -> second).orElse(null);
|
||||
}
|
||||
|
||||
public static Integer getInfiniteStreamLastElementUsingReduce() {
|
||||
Stream<Integer> stream = Stream.iterate(0, i -> i + 1);
|
||||
return stream.limit(20).reduce((first, second) -> second).orElse(null);
|
||||
}
|
||||
|
||||
public static String getLastElementUsingSkip(List<String> valueList) {
|
||||
long count = (long) valueList.size();
|
||||
Stream<String> stream = valueList.stream();
|
||||
return stream.skip(count - 1).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import com.codepoetics.protonpack.Indexed;
|
||||
import com.codepoetics.protonpack.StreamUtils;
|
||||
|
||||
import io.vavr.collection.Stream;
|
||||
import one.util.streamex.EntryStream;
|
||||
|
||||
public class StreamIndices {
|
||||
|
||||
public static List<String> getEvenIndexedStrings(String[] names) {
|
||||
List<String> evenIndexedNames = IntStream.range(0, names.length)
|
||||
.filter(i -> i % 2 == 0)
|
||||
.mapToObj(i -> names[i])
|
||||
.collect(Collectors.toList());
|
||||
return evenIndexedNames;
|
||||
}
|
||||
|
||||
public List<String> getEvenIndexedStringsVersionTwo(List<String> names) {
|
||||
List<String> evenIndexedNames = EntryStream.of(names)
|
||||
.filterKeyValue((index, name) -> index % 2 == 0)
|
||||
.values()
|
||||
.toList();
|
||||
return evenIndexedNames;
|
||||
}
|
||||
|
||||
public static List<Indexed<String>> getEvenIndexedStrings(List<String> names) {
|
||||
List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream())
|
||||
.filter(i -> i.getIndex() % 2 == 0)
|
||||
.collect(Collectors.toList());
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<Indexed<String>> getOddIndexedStrings(List<String> names) {
|
||||
List<Indexed<String>> list = StreamUtils.zipWithIndex(names.stream())
|
||||
.filter(i -> i.getIndex() % 2 == 1)
|
||||
.collect(Collectors.toList());
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<String> getOddIndexedStrings(String[] names) {
|
||||
List<String> oddIndexedNames = IntStream.range(0, names.length)
|
||||
.filter(i -> i % 2 == 1)
|
||||
.mapToObj(i -> names[i])
|
||||
.collect(Collectors.toList());
|
||||
return oddIndexedNames;
|
||||
}
|
||||
|
||||
public static List<String> getOddIndexedStringsVersionTwo(String[] names) {
|
||||
List<String> oddIndexedNames = Stream.of(names)
|
||||
.zipWithIndex()
|
||||
.filter(tuple -> tuple._2 % 2 == 1)
|
||||
.map(tuple -> tuple._1)
|
||||
.toJavaList();
|
||||
return oddIndexedNames;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.baeldung.stream.filter;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import java.io.IOException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
public class Customer {
|
||||
private String name;
|
||||
private int points;
|
||||
private String profilePhotoUrl;
|
||||
|
||||
public Customer(String name, int points) {
|
||||
this(name, points, "");
|
||||
}
|
||||
|
||||
public Customer(String name, int points, String profilePhotoUrl) {
|
||||
this.name = name;
|
||||
this.points = points;
|
||||
this.profilePhotoUrl = profilePhotoUrl;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getPoints() {
|
||||
return points;
|
||||
}
|
||||
|
||||
public boolean hasOver(int points) {
|
||||
return this.points > points;
|
||||
}
|
||||
|
||||
public boolean hasOverHundredPoints() {
|
||||
return this.points > 100;
|
||||
}
|
||||
|
||||
public boolean hasValidProfilePhoto() throws IOException {
|
||||
URL url = new URL(this.profilePhotoUrl);
|
||||
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
|
||||
return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
|
||||
}
|
||||
|
||||
public boolean hasValidProfilePhotoWithoutCheckedException() {
|
||||
try {
|
||||
URL url = new URL(this.profilePhotoUrl);
|
||||
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
|
||||
return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.stream.sum;
|
||||
|
||||
public class ArithmeticUtils {
|
||||
|
||||
public static int add(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.stream.sum;
|
||||
|
||||
public class Item {
|
||||
|
||||
private int id;
|
||||
private Integer price;
|
||||
|
||||
public Item(int id, Integer price) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
// Standard getters and setters
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Integer getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(Integer price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.stream.sum;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StreamSumCalculator {
|
||||
|
||||
public static Integer getSumUsingCustomizedAccumulator(List<Integer> integers) {
|
||||
return integers.stream()
|
||||
.reduce(0, ArithmeticUtils::add);
|
||||
|
||||
}
|
||||
|
||||
public static Integer getSumUsingJavaAccumulator(List<Integer> integers) {
|
||||
return integers.stream()
|
||||
.reduce(0, Integer::sum);
|
||||
|
||||
}
|
||||
|
||||
public static Integer getSumUsingReduce(List<Integer> integers) {
|
||||
return integers.stream()
|
||||
.reduce(0, (a, b) -> a + b);
|
||||
|
||||
}
|
||||
|
||||
public static Integer getSumUsingCollect(List<Integer> integers) {
|
||||
|
||||
return integers.stream()
|
||||
.collect(Collectors.summingInt(Integer::intValue));
|
||||
|
||||
}
|
||||
|
||||
public static Integer getSumUsingSum(List<Integer> integers) {
|
||||
|
||||
return integers.stream()
|
||||
.mapToInt(Integer::intValue)
|
||||
.sum();
|
||||
}
|
||||
|
||||
public static Integer getSumOfMapValues(Map<Object, Integer> map) {
|
||||
|
||||
return map.values()
|
||||
.stream()
|
||||
.mapToInt(Integer::valueOf)
|
||||
.sum();
|
||||
}
|
||||
|
||||
public static Integer getSumIntegersFromString(String str) {
|
||||
|
||||
Integer sum = Arrays.stream(str.split(" "))
|
||||
.filter((s) -> s.matches("\\d+"))
|
||||
.mapToInt(Integer::valueOf)
|
||||
.sum();
|
||||
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.stream.sum;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class StreamSumCalculatorWithObject {
|
||||
|
||||
public static Integer getSumUsingCustomizedAccumulator(List<Item> items) {
|
||||
return items.stream()
|
||||
.map(x -> x.getPrice())
|
||||
.reduce(0, ArithmeticUtils::add);
|
||||
}
|
||||
|
||||
public static Integer getSumUsingJavaAccumulator(List<Item> items) {
|
||||
return items.stream()
|
||||
.map(x -> x.getPrice())
|
||||
.reduce(0, Integer::sum);
|
||||
}
|
||||
|
||||
public static Integer getSumUsingReduce(List<Item> items) {
|
||||
return items.stream()
|
||||
.map(item -> item.getPrice())
|
||||
.reduce(0, (a, b) -> a + b);
|
||||
}
|
||||
|
||||
public static Integer getSumUsingCollect(List<Item> items) {
|
||||
return items.stream()
|
||||
.map(x -> x.getPrice())
|
||||
.collect(Collectors.summingInt(Integer::intValue));
|
||||
}
|
||||
|
||||
public static Integer getSumUsingSum(List<Item> items) {
|
||||
return items.stream()
|
||||
.mapToInt(x -> x.getPrice())
|
||||
.sum();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.conversion;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
|
||||
|
||||
public class IterableStreamConversionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIterable_whenConvertedToStream_thenNotNull() {
|
||||
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||
|
||||
Assert.assertNotNull(StreamSupport.stream(iterable.spliterator(), false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertedToList_thenCorrect() {
|
||||
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||
|
||||
List<String> result = StreamSupport.stream(iterable.spliterator(), false).map(String::toUpperCase).collect(Collectors.toList());
|
||||
|
||||
assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package com.baeldung.protonpack;
|
||||
|
||||
import com.codepoetics.protonpack.Indexed;
|
||||
import com.codepoetics.protonpack.StreamUtils;
|
||||
import com.codepoetics.protonpack.collectors.CollectorUtils;
|
||||
import com.codepoetics.protonpack.collectors.NonUniqueValueException;
|
||||
import com.codepoetics.protonpack.selectors.Selectors;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.Arrays.stream;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
|
||||
|
||||
public class ProtonpackUnitTest {
|
||||
@Test
|
||||
public void whenTakeWhile_thenTakenWhile() {
|
||||
Stream<Integer> streamOfInt = Stream.iterate(1, i -> i + 1);
|
||||
List<Integer> result = StreamUtils.takeWhile(streamOfInt, i -> i < 5).collect(Collectors.toList());
|
||||
assertThat(result).contains(1, 2, 3, 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTakeUntil_thenTakenUntil() {
|
||||
Stream<Integer> streamOfInt = Stream.iterate(1, i -> i + 1);
|
||||
List<Integer> result = StreamUtils.takeUntil(streamOfInt, i -> i > 50).collect(Collectors.toList());
|
||||
assertThat(result).contains(10, 20, 30, 40);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleStream_whenZipped_thenZipped() {
|
||||
String[] clubs = {"Juventus", "Barcelona", "Liverpool", "PSG"};
|
||||
String[] players = {"Ronaldo", "Messi", "Salah"};
|
||||
Set<String> zippedFrom2Sources = StreamUtils
|
||||
.zip(stream(clubs), stream(players), (club, player) -> club + " " + player)
|
||||
.collect(Collectors.toSet());
|
||||
assertThat(zippedFrom2Sources).contains("Juventus Ronaldo", "Barcelona Messi", "Liverpool Salah");
|
||||
|
||||
String[] leagues = {"Serie A", "La Liga", "Premier League"};
|
||||
Set<String> zippedFrom3Sources = StreamUtils.zip(stream(clubs), stream(players), stream(leagues),
|
||||
(club, player, league) -> club + " " + player + " " + league).collect(Collectors.toSet());
|
||||
assertThat(zippedFrom3Sources).contains("Juventus Ronaldo Serie A", "Barcelona Messi La Liga",
|
||||
"Liverpool Salah Premier League");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenZippedWithIndex_thenZippedWithIndex() {
|
||||
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool");
|
||||
Set<Indexed<String>> zipsWithIndex = StreamUtils.zipWithIndex(streamOfClubs).collect(Collectors.toSet());
|
||||
assertThat(zipsWithIndex).contains(Indexed.index(0, "Juventus"), Indexed.index(1, "Barcelona"),
|
||||
Indexed.index(2, "Liverpool"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleStream_whenMerged_thenMerged() {
|
||||
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool", "PSG");
|
||||
Stream<String> streamOfPlayers = Stream.of("Ronaldo", "Messi", "Salah");
|
||||
Stream<String> streamOfLeagues = Stream.of("Serie A", "La Liga", "Premier League");
|
||||
|
||||
Set<String> merged = StreamUtils.merge(() -> "", (valOne, valTwo) -> valOne + " " + valTwo, streamOfClubs,
|
||||
streamOfPlayers, streamOfLeagues).collect(Collectors.toSet());
|
||||
|
||||
assertThat(merged)
|
||||
.contains(" Juventus Ronaldo Serie A", " Barcelona Messi La Liga", " Liverpool Salah Premier League",
|
||||
" PSG");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleStream_whenMergedToList_thenMergedToList() {
|
||||
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "PSG");
|
||||
Stream<String> streamOfPlayers = Stream.of("Ronaldo", "Messi");
|
||||
|
||||
List<List<String>> mergedListOfList = StreamUtils.mergeToList(streamOfClubs, streamOfPlayers)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(mergedListOfList.get(0)).isInstanceOf(List.class);
|
||||
assertThat(mergedListOfList.get(0)).containsExactly("Juventus", "Ronaldo");
|
||||
assertThat(mergedListOfList.get(1)).containsExactly("Barcelona", "Messi");
|
||||
assertThat(mergedListOfList.get(2)).containsExactly("PSG");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleStream_whenInterleaved_thenInterleaved() {
|
||||
Stream<String> streamOfClubs = Stream.of("Juventus", "Barcelona", "Liverpool");
|
||||
Stream<String> streamOfPlayers = Stream.of("Ronaldo", "Messi");
|
||||
Stream<String> streamOfLeagues = Stream.of("Serie A", "La Liga");
|
||||
|
||||
List<String> interleavedList = StreamUtils
|
||||
.interleave(Selectors.roundRobin(), streamOfClubs, streamOfPlayers, streamOfLeagues)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(interleavedList)
|
||||
.hasSize(7)
|
||||
.containsExactly("Juventus", "Ronaldo", "Serie A", "Barcelona", "Messi", "La Liga", "Liverpool");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSkippedUntil_thenSkippedUntil() {
|
||||
Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
|
||||
List<Integer> skippedUntilGreaterThan5 = StreamUtils.skipUntil(stream(numbers), i -> i > 5)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(skippedUntilGreaterThan5).containsExactly(6, 7, 8, 9, 10);
|
||||
|
||||
List<Integer> skippedUntilLessThanEquals5 = StreamUtils.skipUntil(stream(numbers), i -> i <= 5)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(skippedUntilLessThanEquals5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSkippedWhile_thenSkippedWhile() {
|
||||
Integer[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
|
||||
List<Integer> skippedWhileLessThanEquals5 = StreamUtils.skipWhile(stream(numbers), i -> i <= 5)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(skippedWhileLessThanEquals5).containsExactly(6, 7, 8, 9, 10);
|
||||
|
||||
List<Integer> skippedWhileGreaterThan5 = StreamUtils.skipWhile(stream(numbers), i -> i > 5)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(skippedWhileGreaterThan5).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFibonacciGenerator_whenUnfolded_thenUnfolded() {
|
||||
Stream<Integer> unfolded = StreamUtils.unfold(2, i -> (i < 100) ? Optional.of(i * i) : Optional.empty());
|
||||
|
||||
assertThat(unfolded.collect(Collectors.toList())).containsExactly(2, 4, 16, 256);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenWindowed_thenWindowed() {
|
||||
Integer[] numbers = {1, 2, 3, 4, 5, 6, 7};
|
||||
|
||||
List<List<Integer>> windowedWithSkip1 = StreamUtils.windowed(stream(numbers), 3, 1)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(windowedWithSkip1)
|
||||
.containsExactly(asList(1, 2, 3), asList(2, 3, 4), asList(3, 4, 5), asList(4, 5, 6),
|
||||
asList(5, 6, 7));
|
||||
|
||||
List<List<Integer>> windowedWithSkip2 = StreamUtils.windowed(stream(numbers), 3, 2)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(windowedWithSkip2).containsExactly(asList(1, 2, 3), asList(3, 4, 5), asList(5, 6, 7));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAggregated_thenAggregated() {
|
||||
Integer[] numbers = {1, 2, 2, 3, 4, 4, 4, 5};
|
||||
List<List<Integer>> aggregated = StreamUtils
|
||||
.aggregate(stream(numbers), (int1, int2) -> int1.compareTo(int2) == 0)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(aggregated).containsExactly(asList(1), asList(2, 2), asList(3), asList(4, 4, 4), asList(5));
|
||||
|
||||
List<List<Integer>> aggregatedFixSize = StreamUtils.aggregate(stream(numbers), 5).collect(Collectors.toList());
|
||||
assertThat(aggregatedFixSize).containsExactly(asList(1, 2, 2, 3, 4), asList(4, 4, 5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGroupedRun_thenGroupedRun() {
|
||||
Integer[] numbers = {1, 1, 2, 3, 4, 4, 5};
|
||||
List<List<Integer>> grouped = StreamUtils.groupRuns(stream(numbers)).collect(Collectors.toList());
|
||||
assertThat(grouped).containsExactly(asList(1, 1), asList(2), asList(3), asList(4, 4), asList(5));
|
||||
|
||||
Integer[] numbers2 = {1, 2, 3, 1};
|
||||
List<List<Integer>> grouped2 = StreamUtils.groupRuns(stream(numbers2)).collect(Collectors.toList());
|
||||
assertThat(grouped2).containsExactly(asList(1), asList(2), asList(3), asList(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAggregatedOnListCondition_thenAggregatedOnListCondition() {
|
||||
Integer[] numbers = {1, 1, 2, 3, 4, 4, 5};
|
||||
Stream<List<Integer>> aggregated = StreamUtils.aggregateOnListCondition(stream(numbers),
|
||||
(currentList, nextInt) -> currentList.stream().mapToInt(Integer::intValue).sum() + nextInt <= 5);
|
||||
assertThat(aggregated).containsExactly(asList(1, 1, 2), asList(3), asList(4), asList(4), asList(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProjectionFunction_whenMaxedBy_thenMaxedBy() {
|
||||
Stream<String> clubs = Stream.of("Juventus", "Barcelona", "PSG");
|
||||
Optional<String> longestName = clubs.collect(CollectorUtils.maxBy(String::length));
|
||||
assertThat(longestName).contains("Barcelona");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStreamOfMultipleElem_whenUniqueCollector_thenValueReturned() {
|
||||
Stream<Integer> singleElement = Stream.of(1);
|
||||
Optional<Integer> unique = singleElement.collect(CollectorUtils.unique());
|
||||
assertThat(unique).contains(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStreamOfMultipleElem_whenUniqueCollector_thenExceptionThrown() {
|
||||
Stream<Integer> multipleElement = Stream.of(1, 2, 3);
|
||||
assertThatExceptionOfType(NonUniqueValueException.class).isThrownBy(() -> {
|
||||
multipleElement.collect(CollectorUtils.unique());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class InfiniteStreamUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenInfiniteStream_whenUseIntermediateLimitMethod_thenShouldTerminateInFiniteTime() {
|
||||
//given
|
||||
Stream<Integer> infiniteStream = Stream.iterate(0, i -> i + 2);
|
||||
|
||||
//when
|
||||
List<Integer> collect = infiniteStream
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(collect, Arrays.asList(0, 2, 4, 6, 8, 10, 12, 14, 16, 18));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInfiniteStreamOfRandomInts_whenUseLimit_shouldTerminateInFiniteTime() {
|
||||
//given
|
||||
Supplier<UUID> randomUUIDSupplier = UUID::randomUUID;
|
||||
Stream<UUID> infiniteStreamOfRandomUUID = Stream.generate(randomUUIDSupplier);
|
||||
|
||||
//when
|
||||
List<UUID> randomInts = infiniteStreamOfRandomUUID
|
||||
.skip(10)
|
||||
.limit(10)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//then
|
||||
assertEquals(randomInts.size(), 10);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamApiUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenList_whenGetLastElementUsingReduce_thenReturnLastElement() {
|
||||
List<String> valueList = new ArrayList<>();
|
||||
valueList.add("Joe");
|
||||
valueList.add("John");
|
||||
valueList.add("Sean");
|
||||
|
||||
String last = StreamApi.getLastElementUsingReduce(valueList);
|
||||
|
||||
assertEquals("Sean", last);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInfiniteStream_whenGetInfiniteStreamLastElementUsingReduce_thenReturnLastElement() {
|
||||
int last = StreamApi.getInfiniteStreamLastElementUsingReduce();
|
||||
assertEquals(19, last);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListAndCount_whenGetLastElementUsingSkip_thenReturnLastElement() {
|
||||
List<String> valueList = new ArrayList<>();
|
||||
valueList.add("Joe");
|
||||
valueList.add("John");
|
||||
valueList.add("Sean");
|
||||
|
||||
String last = StreamApi.getLastElementUsingSkip(valueList);
|
||||
|
||||
assertEquals("Sean", last);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import com.codepoetics.protonpack.Indexed;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamIndicesUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCalled_thenReturnListOfEvenIndexedStrings() {
|
||||
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
|
||||
List<String> expectedResult = Arrays.asList("Afrim", "Besim", "Durim");
|
||||
List<String> actualResult = StreamIndices.getEvenIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalled_thenReturnListOfEvenIndexedStringsVersionTwo() {
|
||||
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
|
||||
List<String> expectedResult = Arrays.asList("Afrim", "Besim", "Durim");
|
||||
List<String> actualResult = StreamIndices.getEvenIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalled_thenReturnListOfOddStrings() {
|
||||
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
|
||||
List<String> expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim");
|
||||
List<String> actualResult = StreamIndices.getOddIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenCalled_thenReturnListOfEvenIndexedStrings() {
|
||||
List<String> names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim");
|
||||
List<Indexed<String>> expectedResult = Arrays
|
||||
.asList(Indexed.index(0, "Afrim"), Indexed.index(2, "Besim"), Indexed
|
||||
.index(4, "Durim"));
|
||||
List<Indexed<String>> actualResult = StreamIndices.getEvenIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenCalled_thenReturnListOfOddIndexedStrings() {
|
||||
List<String> names = Arrays.asList("Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim");
|
||||
List<Indexed<String>> expectedResult = Arrays
|
||||
.asList(Indexed.index(1, "Bashkim"), Indexed.index(3, "Lulzim"), Indexed
|
||||
.index(5, "Shpetim"));
|
||||
List<Indexed<String>> actualResult = StreamIndices.getOddIndexedStrings(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalled_thenReturnListOfOddStringsVersionTwo() {
|
||||
String[] names = {"Afrim", "Bashkim", "Besim", "Lulzim", "Durim", "Shpetim"};
|
||||
List<String> expectedResult = Arrays.asList("Bashkim", "Lulzim", "Shpetim");
|
||||
List<String> actualResult = StreamIndices.getOddIndexedStringsVersionTwo(names);
|
||||
|
||||
assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class SupplierStreamUnitTest {
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void givenStream_whenStreamUsedTwice_thenThrowException() {
|
||||
Stream<String> stringStream = Stream.of("A", "B", "C", "D");
|
||||
Optional<String> result1 = stringStream.findAny();
|
||||
System.out.println(result1.get());
|
||||
Optional<String> result2 = stringStream.findFirst();
|
||||
System.out.println(result2.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whenUsingSupplier_thenNoExceptionIsThrown() {
|
||||
try {
|
||||
Supplier<Stream<String>> streamSupplier = () -> Stream.of("A", "B", "C", "D");
|
||||
Optional<String> result1 = streamSupplier.get().findAny();
|
||||
System.out.println(result1.get());
|
||||
Optional<String> result2 = streamSupplier.get().findFirst();
|
||||
System.out.println(result2.get());
|
||||
} catch (IllegalStateException e) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.baeldung.stream.filter;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Before;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StreamCountUnitTest {
|
||||
|
||||
private List<Customer> customers;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
|
||||
Customer sarah = new Customer("Sarah M.", 200);
|
||||
Customer charles = new Customer("Charles B.", 150);
|
||||
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
|
||||
customers = Arrays.asList(john, sarah, charles, mary);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenCount_thenGetListSize() {
|
||||
long count = customers
|
||||
.stream()
|
||||
.count();
|
||||
|
||||
assertThat(count).isEqualTo(4L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenFilterByPointsOver100AndCount_thenGetTwo() {
|
||||
long countBigCustomers = customers
|
||||
.stream()
|
||||
.filter(c -> c.getPoints() > 100)
|
||||
.count();
|
||||
|
||||
assertThat(countBigCustomers).isEqualTo(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenFilterByPointsAndNameAndCount_thenGetOne() {
|
||||
long count = customers
|
||||
.stream()
|
||||
.filter(c -> c.getPoints() > 10 && c.getName().startsWith("Charles"))
|
||||
.count();
|
||||
|
||||
assertThat(count).isEqualTo(1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenNoneMatchesFilterAndCount_thenGetZero() {
|
||||
long count = customers
|
||||
.stream()
|
||||
.filter(c -> c.getPoints() > 500)
|
||||
.count();
|
||||
|
||||
assertThat(count).isEqualTo(0L);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenUsingMethodOverHundredPointsAndCount_thenGetTwo() {
|
||||
long count = customers
|
||||
.stream()
|
||||
.filter(Customer::hasOverHundredPoints)
|
||||
.count();
|
||||
|
||||
assertThat(count).isEqualTo(2L);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package com.baeldung.stream.filter;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import pl.touk.throwing.ThrowingPredicate;
|
||||
import pl.touk.throwing.exception.WrappedException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
|
||||
|
||||
public class StreamFilterUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenFilterByPoints_thenGetTwo() {
|
||||
Customer john = new Customer("John P.", 15);
|
||||
Customer sarah = new Customer("Sarah M.", 200);
|
||||
Customer charles = new Customer("Charles B.", 150);
|
||||
Customer mary = new Customer("Mary T.", 1);
|
||||
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
|
||||
|
||||
List<Customer> customersWithMoreThan100Points = customers
|
||||
.stream()
|
||||
.filter(c -> c.getPoints() > 100)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(customersWithMoreThan100Points).hasSize(2);
|
||||
assertThat(customersWithMoreThan100Points).contains(sarah, charles);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenFilterByPointsAndName_thenGetOne() {
|
||||
Customer john = new Customer("John P.", 15);
|
||||
Customer sarah = new Customer("Sarah M.", 200);
|
||||
Customer charles = new Customer("Charles B.", 150);
|
||||
Customer mary = new Customer("Mary T.", 1);
|
||||
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
|
||||
|
||||
List<Customer> charlesWithMoreThan100Points = customers
|
||||
.stream()
|
||||
.filter(c -> c.getPoints() > 100 && c
|
||||
.getName()
|
||||
.startsWith("Charles"))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(charlesWithMoreThan100Points).hasSize(1);
|
||||
assertThat(charlesWithMoreThan100Points).contains(charles);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() {
|
||||
Customer john = new Customer("John P.", 15);
|
||||
Customer sarah = new Customer("Sarah M.", 200);
|
||||
Customer charles = new Customer("Charles B.", 150);
|
||||
Customer mary = new Customer("Mary T.", 1);
|
||||
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
|
||||
|
||||
List<Customer> customersWithMoreThan100Points = customers
|
||||
.stream()
|
||||
.filter(Customer::hasOverHundredPoints)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(customersWithMoreThan100Points).hasSize(2);
|
||||
assertThat(customersWithMoreThan100Points).contains(sarah, charles);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() {
|
||||
Optional<Customer> john = Optional.of(new Customer("John P.", 15));
|
||||
Optional<Customer> sarah = Optional.of(new Customer("Sarah M.", 200));
|
||||
Optional<Customer> mary = Optional.of(new Customer("Mary T.", 300));
|
||||
List<Optional<Customer>> customers = Arrays.asList(john, sarah, Optional.empty(), mary, Optional.empty());
|
||||
|
||||
List<Customer> customersWithMoreThan100Points = customers
|
||||
.stream()
|
||||
.flatMap(c -> c
|
||||
.map(Stream::of)
|
||||
.orElseGet(Stream::empty))
|
||||
.filter(Customer::hasOverHundredPoints)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(customersWithMoreThan100Points).hasSize(2);
|
||||
assertThat(customersWithMoreThan100Points).contains(sarah.get(), mary.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() {
|
||||
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
|
||||
Customer sarah = new Customer("Sarah M.", 200);
|
||||
Customer charles = new Customer("Charles B.", 150);
|
||||
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
|
||||
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
|
||||
|
||||
assertThatThrownBy(() -> customers
|
||||
.stream()
|
||||
.filter(Customer::hasValidProfilePhotoWithoutCheckedException)
|
||||
.count()).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() {
|
||||
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
|
||||
Customer sarah = new Customer("Sarah M.", 200);
|
||||
Customer charles = new Customer("Charles B.", 150);
|
||||
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
|
||||
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
|
||||
|
||||
assertThatThrownBy(() -> customers
|
||||
.stream()
|
||||
.filter((ThrowingPredicate.unchecked(Customer::hasValidProfilePhoto)))
|
||||
.collect(Collectors.toList())).isInstanceOf(WrappedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenFilterWithTryCatch_thenGetTwo() {
|
||||
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
|
||||
Customer sarah = new Customer("Sarah M.", 200);
|
||||
Customer charles = new Customer("Charles B.", 150);
|
||||
Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
|
||||
List<Customer> customers = Arrays.asList(john, sarah, charles, mary);
|
||||
|
||||
List<Customer> customersWithValidProfilePhoto = customers
|
||||
.stream()
|
||||
.filter(c -> {
|
||||
try {
|
||||
return c.hasValidProfilePhoto();
|
||||
} catch (IOException e) {
|
||||
//handle exception
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(customersWithValidProfilePhoto).hasSize(2);
|
||||
assertThat(customersWithValidProfilePhoto).contains(john, mary);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenFilterWithTryCatchAndRuntime_thenThrowException() {
|
||||
List<Customer> customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150),
|
||||
new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"));
|
||||
|
||||
assertThatThrownBy(() -> customers
|
||||
.stream()
|
||||
.filter(c -> {
|
||||
try {
|
||||
return c.hasValidProfilePhoto();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
})
|
||||
.collect(Collectors.toList())).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.baeldung.stream.sum;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class StreamSumUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenListOfIntegersWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() {
|
||||
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Integer sum = StreamSumCalculator.getSumUsingCustomizedAccumulator(integers);
|
||||
assertEquals(15, sum.intValue());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfIntegersWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() {
|
||||
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Integer sum = StreamSumCalculator.getSumUsingJavaAccumulator(integers);
|
||||
assertEquals(15, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfIntegersWhenSummingUsingReduceThenCorrectValueReturned() {
|
||||
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Integer sum = StreamSumCalculator.getSumUsingReduce(integers);
|
||||
assertEquals(15, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfIntegersWhenSummingUsingCollectThenCorrectValueReturned() {
|
||||
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Integer sum = StreamSumCalculator.getSumUsingCollect(integers);
|
||||
assertEquals(15, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfIntegersWhenSummingUsingSumThenCorrectValueReturned() {
|
||||
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Integer sum = StreamSumCalculator.getSumUsingSum(integers);
|
||||
assertEquals(15, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfItemsWhenSummingUsingCustomizedAccumulatorThenCorrectValueReturned() {
|
||||
Item item1 = new Item(1, 10);
|
||||
Item item2 = new Item(2, 15);
|
||||
Item item3 = new Item(3, 25);
|
||||
Item item4 = new Item(4, 40);
|
||||
|
||||
List<Item> items = Arrays.asList(item1, item2, item3, item4);
|
||||
|
||||
Integer sum = StreamSumCalculatorWithObject.getSumUsingCustomizedAccumulator(items);
|
||||
assertEquals(90, sum.intValue());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfItemsWhenSummingUsingJavaAccumulatorThenCorrectValueReturned() {
|
||||
Item item1 = new Item(1, 10);
|
||||
Item item2 = new Item(2, 15);
|
||||
Item item3 = new Item(3, 25);
|
||||
Item item4 = new Item(4, 40);
|
||||
|
||||
List<Item> items = Arrays.asList(item1, item2, item3, item4);
|
||||
|
||||
Integer sum = StreamSumCalculatorWithObject.getSumUsingJavaAccumulator(items);
|
||||
assertEquals(90, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfItemsWhenSummingUsingReduceThenCorrectValueReturned() {
|
||||
Item item1 = new Item(1, 10);
|
||||
Item item2 = new Item(2, 15);
|
||||
Item item3 = new Item(3, 25);
|
||||
Item item4 = new Item(4, 40);
|
||||
|
||||
List<Item> items = Arrays.asList(item1, item2, item3, item4);
|
||||
|
||||
Integer sum = StreamSumCalculatorWithObject.getSumUsingReduce(items);
|
||||
assertEquals(90, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfItemsWhenSummingUsingCollectThenCorrectValueReturned() {
|
||||
Item item1 = new Item(1, 10);
|
||||
Item item2 = new Item(2, 15);
|
||||
Item item3 = new Item(3, 25);
|
||||
Item item4 = new Item(4, 40);
|
||||
|
||||
List<Item> items = Arrays.asList(item1, item2, item3, item4);
|
||||
|
||||
Integer sum = StreamSumCalculatorWithObject.getSumUsingCollect(items);
|
||||
assertEquals(90, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfItemsWhenSummingUsingSumThenCorrectValueReturned() {
|
||||
Item item1 = new Item(1, 10);
|
||||
Item item2 = new Item(2, 15);
|
||||
Item item3 = new Item(3, 25);
|
||||
Item item4 = new Item(4, 40);
|
||||
|
||||
List<Item> items = Arrays.asList(item1, item2, item3, item4);
|
||||
|
||||
Integer sum = StreamSumCalculatorWithObject.getSumUsingSum(items);
|
||||
assertEquals(90, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapWhenSummingThenCorrectValueReturned() {
|
||||
Map<Object, Integer> map = new HashMap<Object, Integer>();
|
||||
map.put(1, 10);
|
||||
map.put(2, 15);
|
||||
map.put(3, 25);
|
||||
map.put(4, 40);
|
||||
|
||||
Integer sum = StreamSumCalculator.getSumOfMapValues(map);
|
||||
assertEquals(90, sum.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringWhenSummingThenCorrectValueReturned() {
|
||||
String string = "Item1 10 Item2 25 Item3 30 Item4 45";
|
||||
|
||||
Integer sum = StreamSumCalculator.getSumIntegersFromString(string);
|
||||
assertEquals(110, sum.intValue());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.streamordering;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
import org.openjdk.jmh.runner.options.TimeValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
|
||||
public class BenchmarkManualTest
|
||||
{
|
||||
|
||||
public void
|
||||
launchBenchmark() throws Exception {
|
||||
|
||||
Options opt = new OptionsBuilder()
|
||||
// Specify which benchmarks to run.
|
||||
// You can be more specific if you'd like to run only one benchmark per test.
|
||||
.include(this.getClass().getName() + ".*")
|
||||
// Set the following options as needed
|
||||
.mode (Mode.AverageTime)
|
||||
.timeUnit(TimeUnit.MICROSECONDS)
|
||||
.warmupTime(TimeValue.seconds(1))
|
||||
.warmupIterations(2)
|
||||
.measurementTime(TimeValue.seconds(1))
|
||||
.measurementIterations(2)
|
||||
.threads(2)
|
||||
.forks(1)
|
||||
.shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
//.jvmArgs("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining")
|
||||
//.addProfiler(WinPerfAsmProfiler.class)
|
||||
.build();
|
||||
|
||||
new Runner(opt).run();
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenOrderedStreamInput_whenStreamFiltered_showOpsPerMS(){
|
||||
IntStream.range(1, 100_000_000).parallel().filter(i -> i % 10 == 0).toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenUnorderedStreamInput_whenStreamFiltered_showOpsPerMS(){
|
||||
IntStream.range(1,100_000_000).unordered().parallel().filter(i -> i % 10 == 0).toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenUnorderedStreamInput_whenStreamDistinct_showOpsPerMS(){
|
||||
IntStream.range(1, 1_000_000).unordered().parallel().distinct().toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenOrderedStreamInput_whenStreamDistinct_showOpsPerMS() {
|
||||
//section 5.1.
|
||||
IntStream.range(1, 1_000_000).parallel().distinct().toArray();
|
||||
}
|
||||
|
||||
|
||||
// The JMH samples are the best documentation for how to use it
|
||||
// http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/
|
||||
@State(Scope.Thread)
|
||||
public static class BenchmarkState
|
||||
{
|
||||
List<Integer> list;
|
||||
|
||||
@Setup(Level.Trial) public void
|
||||
initialize() {
|
||||
|
||||
Random rand = new Random();
|
||||
|
||||
list = new ArrayList<>();
|
||||
for (int i = 0; i < 1000; i++)
|
||||
list.add (rand.nextInt());
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark public void
|
||||
benchmark1 (BenchmarkState state, Blackhole bh) {
|
||||
|
||||
List<Integer> list = state.list;
|
||||
|
||||
for (int i = 0; i < 1000; i++)
|
||||
bh.consume (list.get (i));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.baeldung.streamordering;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamsOrderingUnitTest {
|
||||
|
||||
Logger logger = Logger.getLogger( StreamsOrderingUnitTest.class.getName());
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
logger.setLevel(Level.ALL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoCollections_whenStreamed_thenCheckOutputDifferent(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
|
||||
|
||||
Object[] listOutput = list.stream().toArray();
|
||||
Object[] setOutput = set.stream().toArray();
|
||||
|
||||
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
|
||||
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoCollections_whenStreamedInParallel_thenCheckOutputDifferent(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
|
||||
|
||||
Object[] listOutput = list.stream().parallel().toArray();
|
||||
Object[] setOutput = set.stream().parallel().toArray();
|
||||
|
||||
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
|
||||
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void givenOrderedInput_whenUnorderedAndOrderedCompared_thenCheckUnorderedOutputChanges(){
|
||||
Set<Integer> set = new TreeSet<>(
|
||||
Arrays.asList(-9, -5, -4, -2, 1, 2, 4, 5, 7, 9, 12, 13, 16, 29, 23, 34, 57, 68, 90, 102, 230));
|
||||
|
||||
Object[] orderedArray = set.stream()
|
||||
.parallel()
|
||||
.limit(5)
|
||||
.toArray();
|
||||
Object[] unorderedArray = set.stream()
|
||||
.unordered()
|
||||
.parallel()
|
||||
.limit(5)
|
||||
.toArray();
|
||||
|
||||
logger.info(Arrays.toString(orderedArray));
|
||||
logger.info(Arrays.toString(unorderedArray));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenUnsortedStreamInput_whenStreamSorted_thenCheckOrderChanged(){
|
||||
|
||||
List<Integer> list = Arrays.asList(-3,10,-4,1,3);
|
||||
|
||||
Object[] listOutput = list.stream().toArray();
|
||||
Object[] listOutputSorted = list.stream().sorted().toArray();
|
||||
|
||||
assertEquals("[-3, 10, -4, 1, 3]", Arrays.toString(listOutput));
|
||||
assertEquals("[-4, -3, 1, 3, 10]", Arrays.toString(listOutputSorted));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedStreamInput_whenStreamDistinct_thenShowTimeTaken(){
|
||||
long start, end;
|
||||
start = System.currentTimeMillis();
|
||||
IntStream.range(1,1_000_000).unordered().parallel().distinct().toArray();
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println(String.format("Time taken when unordered: %d ms", (end - start)));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenSameCollection_whenStreamTerminated_thenCheckEachVsEachOrdered(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
|
||||
list.stream().parallel().forEach(e -> logger.log(Level.INFO, e));
|
||||
list.stream().parallel().forEachOrdered(e -> logger.log(Level.INFO, e));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameCollection_whenStreamCollected_thenCheckOutput(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
|
||||
List<String> collectionList = list.stream().parallel().collect(Collectors.toList());
|
||||
Set<String> collectionSet = list.stream().parallel().collect(Collectors.toCollection(TreeSet::new));
|
||||
|
||||
assertEquals("[B, A, C, D, F]", collectionList.toString());
|
||||
assertEquals("[A, B, C, D, F]", collectionSet.toString());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenListIterationOrder_whenStreamCollectedToMap_thenCeckOrderChanged() {
|
||||
List<String> list = Arrays.asList("A", "BB", "CCC");
|
||||
|
||||
Map<String, Integer> hashMap = list.stream().collect(Collectors.toMap(Function.identity(), String::length));
|
||||
|
||||
Object[] keySet = hashMap.keySet().toArray();
|
||||
|
||||
assertEquals("[BB, A, CCC]", Arrays.toString(keySet));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListIteration_whenStreamCollectedtoHashMap_thenCheckOrderMaintained() {
|
||||
List<String> list = Arrays.asList("A", "BB", "CCC", "CCC");
|
||||
|
||||
Map<String, Integer> linkedHashMap = list.stream().collect(Collectors.toMap(
|
||||
Function.identity(),
|
||||
String::length,
|
||||
(u, v) -> u,
|
||||
LinkedHashMap::new
|
||||
));
|
||||
|
||||
Object[] keySet = linkedHashMap.keySet().toArray();
|
||||
|
||||
assertEquals("[A, BB, CCC]", Arrays.toString(keySet));
|
||||
}
|
||||
|
||||
}
|
||||
13
core-java-modules/core-java-streams/src/test/resources/.gitignore
vendored
Normal file
13
core-java-modules/core-java-streams/src/test/resources/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -7,7 +7,7 @@
|
||||
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
|
||||
- [Introduction to Nashorn](http://www.baeldung.com/java-nashorn)
|
||||
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
||||
- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend)
|
||||
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
|
||||
- [How to Find all Getters Returning Null](http://www.baeldung.com/java-getters-returning-null)
|
||||
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
|
||||
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
|
||||
|
||||
Reference in New Issue
Block a user