添加 Java 的 streams 处理模块

This commit is contained in:
YuCheng Hu 2022-05-04 08:27:04 -04:00
parent fa7280f032
commit 18858a282d
23 changed files with 1329 additions and 0 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

@ -0,0 +1,16 @@
## Core Java streams
This module contains articles about the Stream API in Java.
### Relevant Articles:
- [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)
- [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)
- [How to Find all Getters Returning Null](https://www.baeldung.com/java-getters-returning-null)
- More articles: [[next -->]](/../core-java-streams-2)

View File

@ -0,0 +1,113 @@
<?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</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-streams</name>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</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>
<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>
<finalName>core-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-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>
<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>
<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

@ -0,0 +1,32 @@
package com.ossez.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.ossez.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.ossez.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.ossez.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.ossez.stream.sum;
public class ArithmeticUtils {
public static int add(int a, int b) {
return a + b;
}
}

View File

@ -0,0 +1,31 @@
package com.ossez.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.ossez.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.ossez.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

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

View File

@ -0,0 +1,31 @@
package com.ossez.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,47 @@
package com.ossez.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.ossez.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.ossez.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.ossez.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

@ -0,0 +1,72 @@
package com.ossez.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,161 @@
package com.ossez.stream.filter;
import org.assertj.core.api.Assertions;
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());
Assertions.assertThat(customersWithMoreThan100Points).hasSize(2);
Assertions.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());
Assertions.assertThat(charlesWithMoreThan100Points).hasSize(1);
Assertions.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());
Assertions.assertThat(customersWithMoreThan100Points).hasSize(2);
Assertions.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());
Assertions.assertThat(customersWithMoreThan100Points).hasSize(2);
Assertions.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());
Assertions.assertThat(customersWithValidProfilePhoto).hasSize(2);
Assertions.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.ossez.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.ossez.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.ossez.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