[JAVA-12051] Moved code to core-java-streams-simple for ebook (#14889)

This commit is contained in:
panos-kakos 2023-10-13 14:41:35 +03:00 committed by GitHub
parent ff826f0d08
commit ee98df03f4
38 changed files with 200 additions and 76 deletions

View File

@ -5,7 +5,6 @@ This module contains articles about Java 11 core features
### Relevant articles ### Relevant articles
- [Guide To Java 8 Optional](https://www.baeldung.com/java-optional) - [Guide To Java 8 Optional](https://www.baeldung.com/java-optional)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection) - [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [Guide to Java 8s Collectors](https://www.baeldung.com/java-8-collectors)
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features) - [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
- [Getting the Java Version at Runtime](https://www.baeldung.com/get-java-version-runtime) - [Getting the Java Version at Runtime](https://www.baeldung.com/get-java-version-runtime)
- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service) - [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service)

View File

@ -4,5 +4,4 @@
- [Guide to mapMulti in Stream API](https://www.baeldung.com/java-mapmulti) - [Guide to mapMulti in Stream API](https://www.baeldung.com/java-mapmulti)
- [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting) - [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting)
- [New Features in Java 16](https://www.baeldung.com/java-16-new-features) - [New Features in Java 16](https://www.baeldung.com/java-16-new-features)
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
- [Value-Based Classes in Java](https://www.baeldung.com/java-value-based-classes) - [Value-Based Classes in Java](https://www.baeldung.com/java-value-based-classes)

View File

@ -4,12 +4,9 @@ This module contains articles about the Stream API in Java.
### Relevant Articles: ### Relevant Articles:
- [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams) - [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams)
- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction)
- [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany) - [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany)
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)
- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert) - [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert)
- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api) - [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api)
- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams)
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection) - [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
- [How to Add a Single Element to a Stream](https://www.baeldung.com/java-stream-append-prepend) - [How to Add a Single Element to a Stream](https://www.baeldung.com/java-stream-append-prepend)
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream) - [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)

View File

@ -1,6 +1,7 @@
package com.baeldung.streams; package com.baeldung.streams;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -37,6 +38,7 @@ public class Java8StreamApiUnitTest {
assertEquals(list.size() - 1, size); assertEquals(list.size() - 1, size);
} }
@Ignore
@Test @Test
public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() { public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {

View File

@ -2,8 +2,7 @@
This module contains articles about the Stream API in Java. This module contains articles about the Stream API in Java.
### Relevant Articles: ### 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) - [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) - [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams) - [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
@ -12,5 +11,4 @@ This module contains articles about the Stream API in Java.
- [Should We Close a Java Stream?](https://www.baeldung.com/java-stream-close) - [Should We Close a Java Stream?](https://www.baeldung.com/java-stream-close)
- [Returning Stream vs. Collection](https://www.baeldung.com/java-return-stream-collection) - [Returning Stream vs. Collection](https://www.baeldung.com/java-return-stream-collection)
- [Convert a Java Enumeration Into a Stream](https://www.baeldung.com/java-enumeration-to-stream) - [Convert a Java Enumeration Into a Stream](https://www.baeldung.com/java-enumeration-to-stream)
- [When to Use a Parallel Stream in Java](https://www.baeldung.com/java-when-to-use-parallel-stream)
- More articles: [[<-- prev>]](/../core-java-streams-2) - More articles: [[<-- prev>]](/../core-java-streams-2)

View File

@ -0,0 +1,14 @@
## Java Streams Ebook
This module contains articles about Streams that are part of the Java Streams Ebook.
### Relevant Articles
- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction)
- [Guide to Java 8s Collectors](https://www.baeldung.com/java-8-collectors)
- [Java Stream Filter with Lambda Expression](https://www.baeldung.com/java-stream-filter-lambda)
- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams)
- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap)
- [When to Use a Parallel Stream in Java](https://www.baeldung.com/java-when-to-use-parallel-stream)
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)

View File

@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-streams-simple</artifactId>
<name>core-java-streams-simple</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.pivovarit</groupId>
<artifactId>throwing-function</artifactId>
<version>${throwing-function.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-streams-simple</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<throwing-function.version>1.5.1</throwing-function.version>
<maven.compiler.source.version>17</maven.compiler.source.version>
<maven.compiler.target.version>17</maven.compiler.target.version>
<maven.compiler.release>17</maven.compiler.release>
</properties>
</project>

View File

@ -0,0 +1,56 @@
package com.baeldung.streams.filter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
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

@ -1,4 +1,4 @@
package com.baeldung.java_16_features.groupingby; package com.baeldung.streams.groupingby;
import java.util.IntSummaryStatistics; import java.util.IntSummaryStatistics;

View File

@ -1,4 +1,4 @@
package com.baeldung.java_16_features.groupingby; package com.baeldung.streams.groupingby;
public enum BlogPostType { public enum BlogPostType {
NEWS, REVIEW, GUIDE NEWS, REVIEW, GUIDE

View File

@ -1,4 +1,4 @@
package com.baeldung.java_16_features.groupingby; package com.baeldung.streams.groupingby;
import java.util.Objects; import java.util.Objects;

View File

@ -1,8 +1,7 @@
package com.baeldung.reduce.application; package com.baeldung.streams.reduce.application;
import com.baeldung.streams.reduce.entities.User;
import com.baeldung.reduce.entities.User;
import com.baeldung.reduce.utilities.NumberUtils;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;

View File

@ -1,6 +1,6 @@
package com.baeldung.reduce.benchmarks; package com.baeldung.streams.reduce.benchmarks;
import com.baeldung.reduce.entities.User; import com.baeldung.streams.reduce.entities.User;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Benchmark;

View File

@ -1,4 +1,4 @@
package com.baeldung.reduce.entities; package com.baeldung.streams.reduce.entities;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;

View File

@ -1,4 +1,4 @@
package com.baeldung.reduce.entities; package com.baeldung.streams.reduce.entities;
public class Review { public class Review {

View File

@ -1,4 +1,4 @@
package com.baeldung.reduce.entities; package com.baeldung.streams.reduce.entities;
public class User { public class User {

View File

@ -1,4 +1,4 @@
package com.baeldung.reduce.utilities; package com.baeldung.streams.reduce.utilities;
import java.util.List; import java.util.List;
import java.util.function.BiFunction; import java.util.function.BiFunction;

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,4 +1,4 @@
package com.baeldung.collectors; package com.baeldung.streams.collectors;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;

View File

@ -1,4 +1,4 @@
package com.baeldung.stream.filter; package com.baeldung.streams.filter;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import com.pivovarit.function.ThrowingPredicate; import com.pivovarit.function.ThrowingPredicate;
@ -14,10 +14,10 @@ import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
public class StreamFilterUnitTest { class StreamFilterUnitTest {
@Test @Test
public void givenListOfCustomers_whenFilterByPoints_thenGetTwo() { void givenListOfCustomers_whenFilterByPoints_thenGetTwo() {
Customer john = new Customer("John P.", 15); Customer john = new Customer("John P.", 15);
Customer sarah = new Customer("Sarah M.", 200); Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150); Customer charles = new Customer("Charles B.", 150);
@ -53,7 +53,7 @@ public class StreamFilterUnitTest {
} }
@Test @Test
public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() { void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() {
Customer john = new Customer("John P.", 15); Customer john = new Customer("John P.", 15);
Customer sarah = new Customer("Sarah M.", 200); Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150); Customer charles = new Customer("Charles B.", 150);
@ -70,7 +70,7 @@ public class StreamFilterUnitTest {
} }
@Test @Test
public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() { void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() {
Optional<Customer> john = Optional.of(new Customer("John P.", 15)); Optional<Customer> john = Optional.of(new Customer("John P.", 15));
Optional<Customer> sarah = Optional.of(new Customer("Sarah M.", 200)); Optional<Customer> sarah = Optional.of(new Customer("Sarah M.", 200));
Optional<Customer> mary = Optional.of(new Customer("Mary T.", 300)); Optional<Customer> mary = Optional.of(new Customer("Mary T.", 300));
@ -89,7 +89,7 @@ public class StreamFilterUnitTest {
} }
@Test @Test
public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() { void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() {
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
Customer sarah = new Customer("Sarah M.", 200); Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150); Customer charles = new Customer("Charles B.", 150);
@ -103,7 +103,7 @@ public class StreamFilterUnitTest {
} }
@Test @Test
public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() { void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() {
Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"); Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
Customer sarah = new Customer("Sarah M.", 200); Customer sarah = new Customer("Sarah M.", 200);
Customer charles = new Customer("Charles B.", 150); Customer charles = new Customer("Charles B.", 150);

View File

@ -1,6 +1,7 @@
package com.baeldung.streams.flatmap.map; package com.baeldung.streams.flatmap.map;
import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
@ -10,12 +11,12 @@ import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class Java8MapAndFlatMapUnitTest {
class Java8MapAndFlatMapUnitTest {
@Test @Test
public void givenStream_whenCalledMap_thenProduceList() { void givenStream_whenCalledMap_thenProduceList() {
List<String> myList = Stream.of("a", "b") List<String> myList = Stream.of("a", "b")
.map(String::toUpperCase) .map(String::toUpperCase)
.collect(Collectors.toList()); .collect(Collectors.toList());
@ -23,7 +24,7 @@ public class Java8MapAndFlatMapUnitTest {
} }
@Test @Test
public void givenStream_whenCalledFlatMap_thenProduceFlattenedList() throws Exception { void givenStream_whenCalledFlatMap_thenProduceFlattenedList() {
List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b")); List<List<String>> list = Arrays.asList(Arrays.asList("a"), Arrays.asList("b"));
System.out.println(list); System.out.println(list);
@ -33,13 +34,13 @@ public class Java8MapAndFlatMapUnitTest {
} }
@Test @Test
public void givenOptional_whenCalledMap_thenProduceOptional() { void givenOptional_whenCalledMap_thenProduceOptional() {
Optional<String> s = Optional.of("test"); Optional<String> s = Optional.of("test");
assertEquals(Optional.of("TEST"), s.map(String::toUpperCase)); assertEquals(Optional.of("TEST"), s.map(String::toUpperCase));
} }
@Test @Test
public void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() { void givenOptional_whenCalledFlatMap_thenProduceFlattenedOptional() {
assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string") assertEquals(Optional.of(Optional.of("STRING")), Optional.of("string")
.map(s -> Optional.of("STRING"))); .map(s -> Optional.of("STRING")));

View File

@ -1,4 +1,4 @@
package com.baeldung.java_16_features.groupingby; package com.baeldung.streams.groupingby;
import static java.util.Comparator.comparingInt; import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.averagingInt; import static java.util.stream.Collectors.averagingInt;
@ -33,13 +33,13 @@ import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class JavaGroupingByCollectorUnitTest { class JavaGroupingByCollectorUnitTest {
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5), private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15)); new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
@Test @Test
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() { void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream() Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType)); .collect(groupingBy(BlogPost::getType));
@ -52,7 +52,7 @@ public class JavaGroupingByCollectorUnitTest {
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() { void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
Map<BlogPostType, String> postsPerType = posts.stream() Map<BlogPostType, String> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]")))); .collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
@ -62,7 +62,7 @@ public class JavaGroupingByCollectorUnitTest {
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() { void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
Map<BlogPostType, Integer> likesPerType = posts.stream() Map<BlogPostType, Integer> likesPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes))); .collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
@ -75,7 +75,7 @@ public class JavaGroupingByCollectorUnitTest {
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() { void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream() EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList())); .collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
@ -88,7 +88,7 @@ public class JavaGroupingByCollectorUnitTest {
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() { void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream() Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, toSet())); .collect(groupingBy(BlogPost::getType, toSet()));
@ -101,7 +101,7 @@ public class JavaGroupingByCollectorUnitTest {
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() { void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream() ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
.collect(groupingByConcurrent(BlogPost::getType)); .collect(groupingByConcurrent(BlogPost::getType));
@ -114,7 +114,7 @@ public class JavaGroupingByCollectorUnitTest {
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() { void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
Map<BlogPostType, Double> averageLikesPerType = posts.stream() Map<BlogPostType, Double> averageLikesPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes))); .collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
@ -127,7 +127,7 @@ public class JavaGroupingByCollectorUnitTest {
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() { void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream() Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, counting())); .collect(groupingBy(BlogPost::getType, counting()));
@ -140,7 +140,7 @@ public class JavaGroupingByCollectorUnitTest {
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() { void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream() Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes)))); .collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
@ -164,7 +164,7 @@ public class JavaGroupingByCollectorUnitTest {
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() { void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream() Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType))); .collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
@ -189,7 +189,7 @@ public class JavaGroupingByCollectorUnitTest {
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() { void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream() Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes))); .collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
@ -203,7 +203,7 @@ public class JavaGroupingByCollectorUnitTest {
} }
@Test @Test
public void givenAListOfPosts_whenGroupedByComplexMapPairKeyType_thenGetAMapBetweenPairAndList() { void givenAListOfPosts_whenGroupedByComplexMapPairKeyType_thenGetAMapBetweenPairAndList() {
Map<Pair<BlogPostType, String>, List<BlogPost>> postsPerTypeAndAuthor = posts.stream() Map<Pair<BlogPostType, String>, List<BlogPost>> postsPerTypeAndAuthor = posts.stream()
.collect(groupingBy(post -> new ImmutablePair<>(post.getType(), post.getAuthor()))); .collect(groupingBy(post -> new ImmutablePair<>(post.getType(), post.getAuthor())));

View File

@ -1,4 +1,4 @@
package com.baeldung.streams; package com.baeldung.streams.map;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;

View File

@ -1,79 +1,80 @@
package com.baeldung.reduce; package com.baeldung.streams.reduce;
import com.baeldung.reduce.entities.User; import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.reduce.utilities.NumberUtils;
import org.junit.Test; import com.baeldung.streams.reduce.entities.User;
import com.baeldung.streams.reduce.utilities.NumberUtils;
import org.junit.jupiter.api.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Assertions.assertThat; class StreamReduceUnitTest {
public class StreamReduceUnitTest {
@Test @Test
public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() { void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element); int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
assertThat(result).isEqualTo(21); assertThat(result).isEqualTo(21);
} }
@Test @Test
public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() { void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result = numbers.stream().reduce(0, Integer::sum); int result = numbers.stream().reduce(0, Integer::sum);
assertThat(result).isEqualTo(21); assertThat(result).isEqualTo(21);
} }
@Test @Test
public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() { void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e"); List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.stream().reduce("", (partialString, element) -> partialString + element); String result = letters.stream().reduce("", (partialString, element) -> partialString + element);
assertThat(result).isEqualTo("abcde"); assertThat(result).isEqualTo("abcde");
} }
@Test @Test
public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() { void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e"); List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.stream().reduce("", String::concat); String result = letters.stream().reduce("", String::concat);
assertThat(result).isEqualTo("abcde"); assertThat(result).isEqualTo("abcde");
} }
@Test @Test
public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() { void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e"); List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase()); String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
assertThat(result).isEqualTo("ABCDE"); assertThat(result).isEqualTo("ABCDE");
} }
@Test @Test
public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() { void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35)); List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
assertThat(result).isEqualTo(65); assertThat(result).isEqualTo(65);
} }
@Test @Test
public void givenStringList_whenReduceWithParallelStream_thenCorrect() { void givenStringList_whenReduceWithParallelStream_thenCorrect() {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e"); List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
String result = letters.parallelStream().reduce("", String::concat); String result = letters.parallelStream().reduce("", String::concat);
assertThat(result).isEqualTo("abcde"); assertThat(result).isEqualTo("abcde");
} }
@Test @Test
public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() { void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21); assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
} }
@Test @Test
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() { void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21); assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
} }
@Test @Test
public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() { void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21); assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
} }

View File

@ -9,7 +9,6 @@ This module contains articles about the Stream API in Java.
- [Iterable to Stream in Java](https://www.baeldung.com/java-iterable-to-stream) - [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) - [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) - [Stream Ordering in Java](https://www.baeldung.com/java-stream-ordering)
- [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) - [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) - [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum)
- [How to Find All Getters Returning Null](https://www.baeldung.com/java-getters-returning-null) - [How to Find All Getters Returning Null](https://www.baeldung.com/java-getters-returning-null)

View File

@ -29,11 +29,6 @@
<artifactId>streamex</artifactId> <artifactId>streamex</artifactId>
<version>${streamex.version}</version> <version>${streamex.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.pivovarit</groupId>
<artifactId>throwing-function</artifactId>
<version>${throwing-function.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -62,8 +57,6 @@
<vavr.version>0.10.4</vavr.version> <vavr.version>0.10.4</vavr.version>
<protonpack.version>1.16</protonpack.version> <protonpack.version>1.16</protonpack.version>
<streamex.version>0.8.1</streamex.version> <streamex.version>0.8.1</streamex.version>
<throwing-function.version>1.5.1</throwing-function.version>
<maven.compiler.source>17</maven.compiler.source> <maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target> <maven.compiler.target>17</maven.compiler.target>
</properties> </properties>

View File

@ -166,6 +166,7 @@
<module>core-java-security-algorithms</module> <module>core-java-security-algorithms</module>
<module>core-java-serialization</module> <module>core-java-serialization</module>
<module>core-java-streams</module> <module>core-java-streams</module>
<module>core-java-streams-simple</module>
<module>core-java-streams-3</module> <module>core-java-streams-3</module>
<module>core-java-string-algorithms</module> <module>core-java-string-algorithms</module>
<module>core-java-string-algorithms-2</module> <module>core-java-string-algorithms-2</module>