[JAVA-22519] Created new module libraries-stream and added 5 articles (#15403)
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
*.class
|
||||
|
||||
# Folders #
|
||||
/gensrc
|
||||
/target
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
/bin/
|
||||
@@ -0,0 +1,11 @@
|
||||
## Server
|
||||
|
||||
This module contains articles about stream libraries.
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Merging Streams in Java](https://www.baeldung.com/java-merge-streams)
|
||||
- [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors)
|
||||
- [DistinctBy in the Java Stream API](https://www.baeldung.com/java-streams-distinct-by)
|
||||
- [Introduction to StreamEx](https://www.baeldung.com/streamex)
|
||||
- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack)
|
||||
@@ -0,0 +1,59 @@
|
||||
<?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>libraries-stream</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>libraries-stream</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jooq</groupId>
|
||||
<artifactId>jool</artifactId>
|
||||
<version>${jool.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.pivovarit</groupId>
|
||||
<artifactId>parallel-collectors</artifactId>
|
||||
<version>${parallel-collectors.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.vavr</groupId>
|
||||
<artifactId>vavr</artifactId>
|
||||
<version>${vavr.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.collections</groupId>
|
||||
<artifactId>eclipse-collections</artifactId>
|
||||
<version>${eclipse-collections.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>one.util</groupId>
|
||||
<artifactId>streamex</artifactId>
|
||||
<version>${streamex.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.codepoetics</groupId>
|
||||
<artifactId>protonpack</artifactId>
|
||||
<version>${protonpack.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<jool.version>0.9.12</jool.version>
|
||||
<parallel-collectors.version>1.1.0</parallel-collectors.version>
|
||||
<vavr.version>0.9.0</vavr.version>
|
||||
<eclipse-collections.version>8.2.0</eclipse-collections.version>
|
||||
<streamex.version>0.8.1</streamex.version>
|
||||
<protonpack.version>1.15</protonpack.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public class DistinctWithJavaFunction {
|
||||
|
||||
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
|
||||
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
|
||||
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
public class Person {
|
||||
int age;
|
||||
String name;
|
||||
String email;
|
||||
|
||||
public Person(int age, String name, String email) {
|
||||
super();
|
||||
this.age = age;
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("Person [age=");
|
||||
builder.append(age);
|
||||
builder.append(", name=");
|
||||
builder.append(name);
|
||||
builder.append(", email=");
|
||||
builder.append(email);
|
||||
builder.append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((email == null) ? 0 : email.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Person other = (Person) obj;
|
||||
if (email == null) {
|
||||
if (other.email != null)
|
||||
return false;
|
||||
} else if (!email.equals(other.email))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.streamex;
|
||||
|
||||
public class Role {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.streamex;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import one.util.streamex.DoubleStreamEx;
|
||||
import one.util.streamex.EntryStream;
|
||||
import one.util.streamex.IntStreamEx;
|
||||
import one.util.streamex.StreamEx;
|
||||
|
||||
public class StreamEX {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Collector shortcut methods (toList, toSet, groupingBy, joining, etc.)
|
||||
List<User> users = Arrays.asList(new User("name"), new User(), new User());
|
||||
users.stream().map(User::getName).collect(Collectors.toList());
|
||||
List<String> userNames = StreamEx.of(users).map(User::getName).toList();
|
||||
Map<Role, List<User>> role2users = StreamEx.of(users).groupingBy(User::getRole);
|
||||
StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3"
|
||||
// Selecting stream elements of specific type
|
||||
List usersAndRoles = Arrays.asList(new User(), new Role());
|
||||
List<Role> roles = IntStreamEx.range(usersAndRoles.size()).mapToObj(usersAndRoles::get).select(Role.class).toList();
|
||||
System.out.println(roles);
|
||||
// adding elements to Stream
|
||||
List<String> appendedUsers = StreamEx.of(users).map(User::getName).prepend("(none)").append("LAST").toList();
|
||||
System.out.println(appendedUsers);
|
||||
// Removing unwanted elements and using the stream as Iterable:
|
||||
for (String line : StreamEx.of(users).map(User::getName).nonNull()) {
|
||||
System.out.println(line);
|
||||
}
|
||||
// Selecting map keys by value predicate:
|
||||
Map<String, Role> nameToRole = new HashMap<>();
|
||||
nameToRole.put("first", new Role());
|
||||
nameToRole.put("second", null);
|
||||
Set<String> nonNullRoles = StreamEx.ofKeys(nameToRole, Objects::nonNull).toSet();
|
||||
System.out.println(nonNullRoles);
|
||||
// Operating on key-value pairs:
|
||||
Map<User, List<Role>> users2roles = transformMap(role2users);
|
||||
Map<String, String> mapToString = EntryStream.of(users2roles).mapKeys(String::valueOf).mapValues(String::valueOf).toMap();
|
||||
// Support of byte/char/short/float types:
|
||||
short[] src = { 1, 2, 3 };
|
||||
char[] output = IntStreamEx.of(src).map(x -> x * 5).toCharArray();
|
||||
}
|
||||
|
||||
public double[] getDiffBetweenPairs(double... numbers) {
|
||||
return DoubleStreamEx.of(numbers).pairMap((a, b) -> b - a).toArray();
|
||||
}
|
||||
|
||||
public static Map<User, List<Role>> transformMap(Map<Role, List<User>> role2users) {
|
||||
Map<User, List<Role>> users2roles = EntryStream.of(role2users).flatMapValues(List::stream).invert().grouping();
|
||||
return users2roles;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.streamex;
|
||||
|
||||
public class User {
|
||||
|
||||
int id;
|
||||
String name;
|
||||
Role role = new Role();
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Role getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(Role role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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>
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.collections.impl.block.factory.HashingStrategies;
|
||||
import org.eclipse.collections.impl.utility.ListIterate;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DistinctWithEclipseCollectionsUnitTest {
|
||||
List<Person> personList;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
personList = PersonDataGenerator.getPersonListWithFakeValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByName_thenSizeShouldBe4() {
|
||||
List<Person> personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromFunction(Person::getName));
|
||||
assertTrue(personListFiltered.size() == 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByAge_thenSizeShouldBe2() {
|
||||
List<Person> personListFiltered = ListIterate.distinct(personList, HashingStrategies.fromIntFunction(Person::getAge));
|
||||
assertTrue(personListFiltered.size() == 2);
|
||||
}
|
||||
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
import static com.baeldung.distinct.DistinctWithJavaFunction.distinctByKey;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DistinctWithJavaFunctionUnitTest {
|
||||
List<Person> personList;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
personList = PersonDataGenerator.getPersonListWithFakeValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByName_thenSizeShouldBe4() {
|
||||
List<Person> personListFiltered = personList.stream().filter(distinctByKey(p -> p.getName())).collect(Collectors.toList());
|
||||
assertTrue(personListFiltered.size() == 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByAge_thenSizeShouldBe2() {
|
||||
List<Person> personListFiltered = personList.stream().filter(distinctByKey(p -> p.getAge())).collect(Collectors.toList());
|
||||
assertTrue(personListFiltered.size() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListWithDefaultDistinct_thenSizeShouldBe5() {
|
||||
List<Person> personListFiltered = personList.stream().distinct().collect(Collectors.toList());
|
||||
assertTrue(personListFiltered.size() == 5);
|
||||
}
|
||||
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import one.util.streamex.StreamEx;
|
||||
|
||||
public class DistinctWithStreamexUnitTest {
|
||||
List<Person> personList;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
personList = PersonDataGenerator.getPersonListWithFakeValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByName_thenSizeShouldBe4() {
|
||||
List<Person> personListFiltered = StreamEx.of(personList).distinct(Person::getName).toList();
|
||||
assertTrue(personListFiltered.size() == 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByAge_thenSizeShouldBe2() {
|
||||
List<Person> personListFiltered = StreamEx.of(personList).distinct(Person::getAge).toList();
|
||||
assertTrue(personListFiltered.size() == 2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DistinctWithVavrUnitTest {
|
||||
List<Person> personList;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
personList = PersonDataGenerator.getPersonListWithFakeValues();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByName_thenSizeShouldBe4() {
|
||||
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getName).toJavaList();
|
||||
assertTrue(personListFiltered.size() == 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFilterListByAge_thenSizeShouldBe2() {
|
||||
List<Person> personListFiltered = io.vavr.collection.List.ofAll(personList).distinctBy(Person::getAge).toJavaList();
|
||||
assertTrue(personListFiltered.size() == 2);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.distinct;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class PersonDataGenerator {
|
||||
|
||||
public static List<Person> getPersonListWithFakeValues() {
|
||||
// @formatter:off
|
||||
return Arrays.asList(
|
||||
new Person(20, "Jhon", "[email protected]"),
|
||||
new Person(20, "Jhon", "[email protected]"),
|
||||
new Person(20, "Jhon", "[email protected]"),
|
||||
new Person(21, "Tom", "[email protected]"),
|
||||
new Person(21, "Mark", "[email protected]"),
|
||||
new Person(20, "Julia", "[email protected]"));
|
||||
// @formatter:on
|
||||
}
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
package com.baeldung.parallel_collectors;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.pivovarit.collectors.ParallelCollectors.parallel;
|
||||
import static com.pivovarit.collectors.ParallelCollectors.parallelOrdered;
|
||||
import static com.pivovarit.collectors.ParallelCollectors.parallelToCollection;
|
||||
import static com.pivovarit.collectors.ParallelCollectors.parallelToList;
|
||||
import static com.pivovarit.collectors.ParallelCollectors.parallelToMap;
|
||||
import static com.pivovarit.collectors.ParallelCollectors.parallelToStream;
|
||||
|
||||
public class ParallelCollectorsUnitTest {
|
||||
|
||||
@Test
|
||||
public void shouldProcessInParallelWithStreams() {
|
||||
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||
|
||||
List<String> results = ids.parallelStream()
|
||||
.map(i -> fetchById(i))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
System.out.println(results);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldProcessInParallelWithParallelCollectors() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
|
||||
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||
|
||||
CompletableFuture<List<String>> results = ids.stream()
|
||||
.collect(parallelToList(ParallelCollectorsUnitTest::fetchById, executor, 4));
|
||||
|
||||
System.out.println(results.join());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldCollectToList() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
|
||||
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||
|
||||
List<String> results = ids.stream()
|
||||
.collect(parallelToList(ParallelCollectorsUnitTest::fetchById, executor, 4))
|
||||
.join();
|
||||
|
||||
System.out.println(results); // [user-1, user-2, user-3]
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldCollectToCollection() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
|
||||
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||
|
||||
List<String> results = ids.stream()
|
||||
.collect(parallelToCollection(i -> fetchById(i), LinkedList::new, executor, 4))
|
||||
.join();
|
||||
|
||||
System.out.println(results); // [user-1, user-2, user-3]
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldCollectToStream() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
|
||||
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||
|
||||
Map<Integer, List<String>> results = ids.stream()
|
||||
.collect(parallelToStream(i -> fetchById(i), executor, 4))
|
||||
.thenApply(stream -> stream.collect(Collectors.groupingBy(i -> i.length())))
|
||||
.join();
|
||||
|
||||
System.out.println(results); // [user-1, user-2, user-3]
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldStreamInCompletionOrder() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
|
||||
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||
|
||||
ids.stream()
|
||||
.collect(parallel(ParallelCollectorsUnitTest::fetchByIdWithRandomDelay, executor, 4))
|
||||
.forEach(System.out::println);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldStreamInOriginalOrder() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
|
||||
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||
|
||||
ids.stream()
|
||||
.collect(parallelOrdered(ParallelCollectorsUnitTest::fetchByIdWithRandomDelay, executor, 4))
|
||||
.forEach(System.out::println);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldCollectToMap() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
|
||||
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||
|
||||
Map<Integer, String> results = ids.stream()
|
||||
.collect(parallelToMap(i -> i, ParallelCollectorsUnitTest::fetchById, executor, 4))
|
||||
.join();
|
||||
|
||||
System.out.println(results); // {1=user-1, 2=user-2, 3=user-3}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldCollectToTreeMap() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
|
||||
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||
|
||||
Map<Integer, String> results = ids.stream()
|
||||
.collect(parallelToMap(i -> i, ParallelCollectorsUnitTest::fetchById, TreeMap::new, executor, 4))
|
||||
.join();
|
||||
|
||||
System.out.println(results); // {1=user-1, 2=user-2, 3=user-3}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldCollectToTreeMapAndResolveClashes() {
|
||||
ExecutorService executor = Executors.newFixedThreadPool(10);
|
||||
|
||||
List<Integer> ids = Arrays.asList(1, 2, 3);
|
||||
|
||||
Map<Integer, String> results = ids.stream()
|
||||
.collect(parallelToMap(i -> i, ParallelCollectorsUnitTest::fetchById, TreeMap::new, (s1, s2) -> s1, executor, 4))
|
||||
.join();
|
||||
|
||||
System.out.println(results); // {1=user-1, 2=user-2, 3=user-3}
|
||||
}
|
||||
|
||||
private static String fetchById(int id) {
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
// ignore shamelessly
|
||||
}
|
||||
|
||||
return "user-" + id;
|
||||
}
|
||||
|
||||
private static String fetchByIdWithRandomDelay(int id) {
|
||||
try {
|
||||
Thread.sleep(ThreadLocalRandom.current().nextInt(1000));
|
||||
} catch (InterruptedException e) {
|
||||
// ignore shamelessly
|
||||
}
|
||||
|
||||
return "user-" + id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package com.baeldung.protonpack;
|
||||
|
||||
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;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
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;
|
||||
|
||||
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());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import org.jooq.lambda.Seq;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class JoolMergeStreamsUnitTest {
|
||||
@Test
|
||||
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
|
||||
Stream<Integer> seq1 = Stream.of(1, 3, 5);
|
||||
Stream<Integer> seq2 = Stream.of(2, 4, 6);
|
||||
|
||||
Stream<Integer> resultingSeq = Seq.ofType(seq1, Integer.class).append(seq2);
|
||||
|
||||
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingSeq.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() {
|
||||
Stream<String> seq = Stream.of("foo", "bar");
|
||||
Stream<String> openingBracketSeq = Stream.of("[");
|
||||
Stream<String> closingBracketSeq = Stream.of("]");
|
||||
|
||||
Stream<String> resultingStream = Seq.ofType(seq, String.class).append(closingBracketSeq).prepend(openingBracketSeq);
|
||||
|
||||
Assert.assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MergeStreamsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
|
||||
Stream<Integer> stream1 = Stream.of(1, 3, 5);
|
||||
Stream<Integer> stream2 = Stream.of(2, 4, 6);
|
||||
|
||||
Stream<Integer> resultingStream = Stream.concat(stream1, stream2);
|
||||
|
||||
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenThreeStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() {
|
||||
Stream<Integer> stream1 = Stream.of(1, 3, 5);
|
||||
Stream<Integer> stream2 = Stream.of(2, 4, 6);
|
||||
Stream<Integer> stream3 = Stream.of(18, 15, 36);
|
||||
|
||||
Stream<Integer> resultingStream = Stream.concat(Stream.concat(stream1, stream2), stream3);
|
||||
|
||||
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36), resultingStream.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFourStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() {
|
||||
Stream<Integer> stream1 = Stream.of(1, 3, 5);
|
||||
Stream<Integer> stream2 = Stream.of(2, 4, 6);
|
||||
Stream<Integer> stream3 = Stream.of(18, 15, 36);
|
||||
Stream<Integer> stream4 = Stream.of(99);
|
||||
|
||||
Stream<Integer> resultingStream = Stream.of(stream1, stream2, stream3, stream4).flatMap(Function.identity());
|
||||
|
||||
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList()));
|
||||
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.streamex;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import one.util.streamex.StreamEx;
|
||||
|
||||
public class StreamExMergeStreamsUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
|
||||
Stream<Integer> stream1 = Stream.of(1, 3, 5);
|
||||
Stream<Integer> stream2 = Stream.of(2, 4, 6);
|
||||
|
||||
Stream<Integer> resultingStream = StreamEx.of(stream1).append(stream2);
|
||||
|
||||
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6), resultingStream.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFourStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() {
|
||||
Stream<Integer> stream1 = Stream.of(1, 3, 5);
|
||||
Stream<Integer> stream2 = Stream.of(2, 4, 6);
|
||||
Stream<Integer> stream3 = Stream.of(18, 15, 36);
|
||||
Stream<Integer> stream4 = Stream.of(99);
|
||||
|
||||
Stream<Integer> resultingStream = StreamEx.of(stream1).append(stream2).append(stream3).append(stream4);
|
||||
|
||||
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99), resultingStream.collect(Collectors.toList()));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() {
|
||||
Stream<String> stream1 = Stream.of("foo", "bar");
|
||||
Stream<String> openingBracketStream = Stream.of("[");
|
||||
Stream<String> closingBracketStream = Stream.of("]");
|
||||
|
||||
Stream<String> resultingStream = StreamEx.of(stream1).append(closingBracketStream).prepend(openingBracketStream);
|
||||
|
||||
assertEquals(Arrays.asList("[", "foo", "bar", "]"), resultingStream.collect(Collectors.toList()));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user