Split or move java-streams module

This commit is contained in:
catalin-burcea
2019-10-27 11:09:34 +02:00
parent 699cc1027e
commit 62089a7abb
67 changed files with 881 additions and 1046 deletions

View 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)

View 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>

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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 + '}';
}
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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>

View File

@@ -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]");
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -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"));
}
}

View File

@@ -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++;
}
}

View File

@@ -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
}
}

View File

@@ -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) {
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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"));
}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}
}