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

View File

@@ -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 8s 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)

View File

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

View File

@@ -1,84 +0,0 @@
package com.baeldung.forEach;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
class ReverseList extends ArrayList<String> {
List<String> list = Arrays.asList("A", "B", "C", "D");
Consumer<String> removeElement = s -> {
System.out.println(s + " " + list.size());
if (s != null && s.equals("A")) {
list.remove("D");
}
};
@Override
public Iterator<String> iterator() {
final int startIndex = this.size() - 1;
final List<String> list = this;
return new Iterator<String>() {
int currentIndex = startIndex;
@Override
public boolean hasNext() {
return currentIndex >= 0;
}
@Override
public String next() {
String next = list.get(currentIndex);
currentIndex--;
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public void forEach(Consumer<? super String> action) {
for (String s : this) {
action.accept(s);
}
}
public void iterateParallel() {
list.forEach(System.out::print);
System.out.print(" ");
list.parallelStream().forEach(System.out::print);
}
public void iterateReverse() {
List<String> myList = new ReverseList();
myList.addAll(list);
myList.forEach(System.out::print);
System.out.print(" ");
myList.stream().forEach(System.out::print);
}
public void removeInCollectionForEach() {
list.forEach(removeElement);
}
public void removeInStreamForEach() {
list.stream().forEach(removeElement);
}
public static void main(String[] argv) {
ReverseList collectionForEach = new ReverseList();
collectionForEach.iterateParallel();
collectionForEach.iterateReverse();
collectionForEach.removeInCollectionForEach();
collectionForEach.removeInStreamForEach();
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,8 @@
package com.baeldung.stream.sum;
public class ArithmeticUtils {
public static int add(int a, int b) {
return a + b;
}
}

View File

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

View File

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

View File

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

View File

@@ -1,231 +0,0 @@
package com.baeldung.collectors;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.stream.Collectors.averagingDouble;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.partitioningBy;
import static java.util.stream.Collectors.summarizingDouble;
import static java.util.stream.Collectors.summingDouble;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class Java8CollectorsUnitTest {
private final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
private final List<String> listWithDuplicates = Arrays.asList("a", "bb", "c", "d", "bb");
@Test
public void whenCollectingToList_shouldCollectToList() throws Exception {
final List<String> result = givenList.stream().collect(toList());
assertThat(result).containsAll(givenList);
}
@Test
public void whenCollectingToSet_shouldCollectToSet() throws Exception {
final Set<String> result = givenList.stream().collect(toSet());
assertThat(result).containsAll(givenList);
}
@Test
public void givenContainsDuplicateElements_whenCollectingToSet_shouldAddDuplicateElementsOnlyOnce() throws Exception {
final Set<String> result = listWithDuplicates.stream().collect(toSet());
assertThat(result).hasSize(4);
}
@Test
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
}
@Test
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
assertThatThrownBy(() -> {
givenList.stream().collect(toCollection(ImmutableList::of));
}).isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
}
@Test
public void whenCollectingToMapwWithDuplicates_shouldCollectToMapMergingTheIdenticalItems() throws Exception {
final Map<String, Integer> result = listWithDuplicates.stream().collect(
toMap(
Function.identity(),
String::length,
(item, identicalItem) -> item
)
);
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("c", 1).containsEntry("d", 1);
}
@Test
public void givenContainsDuplicateElements_whenCollectingToMap_shouldThrowException() throws Exception {
assertThatThrownBy(() -> {
listWithDuplicates.stream().collect(toMap(Function.identity(), String::length));
}).isInstanceOf(IllegalStateException.class);
}
@Test
public void whenCollectingAndThen_shouldCollect() throws Exception {
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
}
@Test
public void whenJoining_shouldJoin() throws Exception {
final String result = givenList.stream().collect(joining());
assertThat(result).isEqualTo("abbcccdd");
}
@Test
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
final String result = givenList.stream().collect(joining(" "));
assertThat(result).isEqualTo("a bb ccc dd");
}
@Test
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
}
@Test
public void whenPartitioningBy_shouldPartition() throws Exception {
final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
assertThat(booleanListMap.get(true)).contains("ccc");
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
});
}
@Test
public void whenCounting_shouldCount() throws Exception {
final Long result = givenList.stream().collect(counting());
assertThat(result).isEqualTo(4);
}
@Test
public void whenSummarizing_shouldSummarize() throws Exception {
final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
assertThat(result.getAverage()).isEqualTo(2);
assertThat(result.getCount()).isEqualTo(4);
assertThat(result.getMax()).isEqualTo(3);
assertThat(result.getMin()).isEqualTo(1);
assertThat(result.getSum()).isEqualTo(8);
}
@Test
public void whenAveraging_shouldAverage() throws Exception {
final Double result = givenList.stream().collect(averagingDouble(String::length));
assertThat(result).isEqualTo(2);
}
@Test
public void whenSumming_shouldSum() throws Exception {
final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length));
assertThat(result).isEqualTo(8);
}
@Test
public void whenMaxingBy_shouldMaxBy() throws Exception {
final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
assertThat(result).isPresent().hasValue("dd");
}
@Test
public void whenGroupingBy_shouldGroupBy() throws Exception {
final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
}
@Test
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
}
private static <T> ImmutableSetCollector<T> toImmutableSet() {
return new ImmutableSetCollector<>();
}
private static class ImmutableSetCollector<T> implements Collector<T, ImmutableSet.Builder<T>, ImmutableSet<T>> {
@Override
public Supplier<ImmutableSet.Builder<T>> supplier() {
return ImmutableSet::builder;
}
@Override
public BiConsumer<ImmutableSet.Builder<T>, T> accumulator() {
return ImmutableSet.Builder::add;
}
@Override
public BinaryOperator<ImmutableSet.Builder<T>> combiner() {
return (left, right) -> left.addAll(right.build());
}
@Override
public Function<ImmutableSet.Builder<T>, ImmutableSet<T>> finisher() {
return ImmutableSet.Builder::build;
}
@Override
public Set<Characteristics> characteristics() {
return Sets.immutableEnumSet(Characteristics.UNORDERED);
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,41 +0,0 @@
package com.baeldung.stream.conditional;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Test;
public class StreamForEachIfElseUnitTest {
@Test
public final void givenIntegerStream_whenCheckingIntegerParityWithIfElse_thenEnsureCorrectParity() {
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
ints.stream()
.forEach(i -> {
if (i.intValue() % 2 == 0) {
Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0);
} else {
Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0);
}
});
}
@Test
public final void givenIntegerStream_whenCheckingIntegerParityWithStreamFilter_thenEnsureCorrectParity() {
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Stream<Integer> evenIntegers = ints.stream()
.filter(i -> i.intValue() % 2 == 0);
Stream<Integer> oddIntegers = ints.stream()
.filter(i -> i.intValue() % 2 != 0);
evenIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0));
oddIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0));
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear