[JAVA-6173] Difference Between parallelStream() and stream().parallel() (#13653)

* [JAVA-6173] stream.parallel and parallelStream

* [JAVA-6173] stream.parallel and parallelStream test cases

---------

Co-authored-by: Bhaskar <bhaskar.dastidar@freshworks.com>
This commit is contained in:
Bhaskar Ghosh Dastidar
2023-03-24 23:10:30 +05:30
committed by GitHub
parent c16d9ede8f
commit bde71a9dea
5 changed files with 258 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
package parallelstream;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.streams.parallelstream.Book;
import com.baeldung.streams.parallelstream.MyBookContainer;
import com.baeldung.streams.parallelstream.ParallelStreamApplication;
public class ParallelStreamUnitTest {
@Test
public void givenCollectionWhenCollectionsParallelIsUsedThenReturnCount() {
ParallelStreamApplication parallelStreamApplication = new ParallelStreamApplication();
Assert.assertEquals(parallelStreamApplication.usingCollectionsParallel(generateListOfBooks(), 1974), 2);
}
@Test
public void givenCollectionWhenStreamParallelIsUsedThenReturnCount() {
ParallelStreamApplication parallelStreamApplication = new ParallelStreamApplication();
Assert.assertEquals(parallelStreamApplication.usingStreamParallel(generateListOfBooks(), 1974), 2);
}
@Test
public void givenBookContainerWhenParallelStreamIsUsedThenReturnIncorrectCount() {
ParallelStreamApplication parallelStreamApplication = new ParallelStreamApplication();
Assert.assertNotEquals(parallelStreamApplication.usingWithCustomSpliterator(getBookContainer(), 1974), 2);
}
private List<Book> generateListOfBooks() {
Book book1 = new Book("The Blue Umbrella", "Ruskin Bond", 1974);
Book book2 = new Book("Carrie", "Stephen King", 1974);
Book book3 = new Book("The Psychology of money", "Morgan Housel", 2020);
List<Book> books = List.of(book1, book2, book3);
return books;
}
private MyBookContainer<Book> getBookContainer() {
MyBookContainer<Book> listOfBooks = new MyBookContainer<>(new Book[] { new Book("The Blue Umbrella", "Ruskin Bond", 1974),
new Book("Carrie", "Stephen King", 1974),
new Book("The Psychology of money", "Morgan Housel", 2020)});
return listOfBooks;
}
}