[BAEL-8434] - Moved java stream articles to java-streams module
This commit is contained in:
26
java-streams/.gitignore
vendored
Normal file
26
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
|
||||
15
java-streams/README.md
Normal file
15
java-streams/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
=========
|
||||
|
||||
## Java Streams Cookbooks and Examples
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
|
||||
- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
|
||||
- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams)
|
||||
- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany)
|
||||
- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element)
|
||||
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
|
||||
- [”Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
|
||||
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
|
||||
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
|
||||
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
|
||||
120
java-streams/pom.xml
Normal file
120
java-streams/pom.xml
Normal file
@@ -0,0 +1,120 @@
|
||||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>java-streams</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>java-streams</name>
|
||||
|
||||
<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>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>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<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>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>java-streams</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<compilerArgument>-parameters</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
<protonpack.version>1.13</protonpack.version>
|
||||
<streamex.version>0.6.5</streamex.version>
|
||||
<joda.version>2.10</joda.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<asspectj.version>1.8.9</asspectj.version>
|
||||
</properties>
|
||||
</project>
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
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,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,23 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
48
java-streams/src/main/java/com/baeldung/stream/Product.java
Normal file
48
java-streams/src/main/java/com/baeldung/stream/Product.java
Normal file
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
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,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;
|
||||
}
|
||||
|
||||
}
|
||||
13
java-streams/src/main/resources/logback.xml
Normal file
13
java-streams/src/main/resources/logback.xml
Normal 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>
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.java.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,46 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
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,243 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.stream.Product;
|
||||
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,105 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.Detail;
|
||||
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,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,99 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
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,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,65 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import static java.util.stream.Collectors.collectingAndThen;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.stream.mycollectors.MyImmutableListCollector;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
|
||||
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,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,22 @@
|
||||
package com.baeldung.stream.mycollectors;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
13
java-streams/src/test/resources/.gitignore
vendored
Normal file
13
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
|
||||
Reference in New Issue
Block a user