diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java index d855f775a8..5d4b265500 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java @@ -87,7 +87,7 @@ public class State { void randomPlay() { List availablePositions = this.board.getEmptyPositions(); int totalPossibilities = availablePositions.size(); - int selectRandom = (int) (Math.random() * ((totalPossibilities - 1) + 1)); + int selectRandom = (int) (Math.random() * totalPossibilities); this.board.performMove(this.playerNo, availablePositions.get(selectRandom)); } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java index 20f9e992b5..0ad6510e50 100644 --- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java +++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java @@ -65,7 +65,7 @@ public class Node { public Node getRandomChildNode() { int noOfPossibleMoves = this.childArray.size(); - int selectRandom = (int) (Math.random() * ((noOfPossibleMoves - 1) + 1)); + int selectRandom = (int) (Math.random() * noOfPossibleMoves); return this.childArray.get(selectRandom); } diff --git a/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java b/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java new file mode 100644 index 0000000000..2dd1fdcb75 --- /dev/null +++ b/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java @@ -0,0 +1,35 @@ +package com.baeldung.algorithms.string; + +public class EnglishAlphabetLetters { + + public static boolean checkStringForAllTheLetters(String input) { + boolean[] visited = new boolean[26]; + + int index = 0; + + for (int id = 0; id < input.length(); id++) { + if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') { + index = input.charAt(id) - 'a'; + } else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') { + index = input.charAt(id) - 'A'; + } + visited[index] = true; + } + + for (int id = 0; id < 26; id++) { + if (!visited[id]) { + return false; + } + } + return true; + } + + public static boolean checkStringForAllLetterUsingStream(String input) { + long c = input.toLowerCase().chars().filter(ch -> ch >= 'a' && ch <= 'z').distinct().count(); + return c == 26; + } + + public static void main(String[] args) { + checkStringForAllLetterUsingStream("intit"); + } +} \ No newline at end of file diff --git a/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java similarity index 94% rename from algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java index b0218ae23e..2ac7adc3aa 100644 --- a/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Assert; import org.junit.Test; diff --git a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java similarity index 92% rename from algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java index fa8ecdee77..e819da4b36 100644 --- a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Assert; import org.junit.Test; diff --git a/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java similarity index 98% rename from algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java index 68386278fc..bbc4d4f398 100644 --- a/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Test; diff --git a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java similarity index 98% rename from algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java index e4746b521c..e817d195b3 100644 --- a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import com.baeldung.algorithms.hillclimbing.HillClimbing; import com.baeldung.algorithms.hillclimbing.State; diff --git a/algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java similarity index 99% rename from algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java index 01f9ca2f76..2cda0ccb36 100644 --- a/algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup; import com.baeldung.algorithms.middleelementlookup.Node; diff --git a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java similarity index 98% rename from algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java index 99e962773f..fddccfcd9f 100644 --- a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import com.baeldung.algorithms.automata.*; import org.junit.Test; diff --git a/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java similarity index 90% rename from algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java index 6ee129ece9..2ce7d75e43 100644 --- a/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Assert; import org.junit.Test; diff --git a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java similarity index 94% rename from algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java index c98a8a53f3..dfe015aad2 100755 --- a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java @@ -1,4 +1,4 @@ -package algorithms; +package com.baeldung.algorithms; import org.junit.Assert; diff --git a/algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java similarity index 95% rename from algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java index 74db4236b9..826682d373 100644 --- a/algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java @@ -1,4 +1,4 @@ -package algorithms.binarysearch; +package com.baeldung.algorithms.binarysearch; import java.util.Arrays; import java.util.List; diff --git a/algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java similarity index 98% rename from algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java index edbf21390d..59afed65de 100644 --- a/algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java @@ -1,4 +1,4 @@ -package algorithms.mcts; +package com.baeldung.algorithms.mcts; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java similarity index 95% rename from algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java rename to algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java index c07975bca0..59f0fcf053 100644 --- a/algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java +++ b/algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java @@ -1,4 +1,4 @@ -package algorithms.minimax; +package com.baeldung.algorithms.minimax; import org.junit.Before; import org.junit.Test; diff --git a/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java new file mode 100644 index 0000000000..54863cddc8 --- /dev/null +++ b/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java @@ -0,0 +1,20 @@ +package com.baeldung.algorithms.string; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class EnglishAlphabetLettersUnitTest { + + @Test + void givenString_whenContainsAllCharacter_thenTrue() { + String input = "Farmer jack realized that big yellow quilts were expensive"; + Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllTheLetters(input)); + } + + @Test + void givenString_whenContainsAllCharacter_thenUsingStreamExpectTrue() { + String input = "Farmer jack realized that big yellow quilts were expensive"; + Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllLetterUsingStream(input)); + } + +} diff --git a/core-java-8/README.md b/core-java-8/README.md index e0cd0e7c0a..c94ae36003 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -9,15 +9,10 @@ - [Java 8 New Features](http://www.baeldung.com/java-8-new-features) - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) -- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) -- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) - [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector) - [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern) -- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams) - [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions) -- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany) - [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing) -- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element) - [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro) - [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api) - [Guide To Java 8 Optional](http://www.baeldung.com/java-optional) @@ -27,15 +22,10 @@ - [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max) - [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode) - [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) -- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) -- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception) - [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones) - [Copy a File with Java](http://www.baeldung.com/java-copy-file) - [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods) -- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream) -- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices) - [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency) -- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams) - [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator) - [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection) - [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index ad37cdd7e8..fa0d79e405 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -89,11 +89,6 @@ vavr ${vavr.version} - - one.util - streamex - ${streamex.version} - joda-time joda-time @@ -177,7 +172,6 @@ 1.16.12 0.9.0 1.13 - 0.6.5 2.10 3.6.1 diff --git a/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java b/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java new file mode 100644 index 0000000000..26e5bf0c6b --- /dev/null +++ b/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java @@ -0,0 +1,21 @@ +package com.baeldung.classcastexception; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class ClassCastException { + + public static void main(String[] args) { + + String p1 = new String("John"); + String p2 = new String("Snow"); + String[] strArray = new String[] { p1, p2 }; + ArrayList strList = (ArrayList) Arrays.asList(strArray); + // To fix the ClassCastException at above line, modify the code as: + // List strList = Arrays.asList(strArray); + System.out.println("String list: " + strList); + + } + +} diff --git a/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java b/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java index 5fcbeb3d5f..a3e69b7f6f 100644 --- a/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java +++ b/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java @@ -8,7 +8,7 @@ public class PersonRepository { @Nullable public String findNameById(String id) { - return id == null ? null : "example-name"; + return id == null ? null : "Name"; } public List findAll() throws SQLException { diff --git a/core-java/src/test/java/com/baeldung/throwsexception/PersonRepositoryUnitTest.java b/core-java/src/test/java/com/baeldung/throwsexception/PersonRepositoryUnitTest.java index 6294d40090..0d1859fb1a 100644 --- a/core-java/src/test/java/com/baeldung/throwsexception/PersonRepositoryUnitTest.java +++ b/core-java/src/test/java/com/baeldung/throwsexception/PersonRepositoryUnitTest.java @@ -4,6 +4,7 @@ import org.junit.Test; import java.util.Optional; +import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -29,4 +30,14 @@ public class PersonRepositoryUnitTest { .orElseThrow(Exception::new)); } + @Test + public void whenIdIsNonNull_thenShouldReturnNameUpperCase() throws Exception { + String name = Optional + .ofNullable(personRepository.findNameById("id")) + .map(String::toUpperCase) + .orElseThrow(Exception::new); + + assertEquals("NAME", name); + } + } \ No newline at end of file diff --git a/java-streams/.gitignore b/java-streams/.gitignore new file mode 100644 index 0000000000..3de4cc647e --- /dev/null +++ b/java-streams/.gitignore @@ -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 \ No newline at end of file diff --git a/java-streams/README.md b/java-streams/README.md new file mode 100644 index 0000000000..4bfcabb7cf --- /dev/null +++ b/java-streams/README.md @@ -0,0 +1,14 @@ +========= + +## Java Streams Cookbooks and Examples + +### Relevant Articles: +- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) +- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) +- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams) +- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany) +- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element) +- [”Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception) +- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream) +- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices) +- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams) diff --git a/java-streams/pom.xml b/java-streams/pom.xml new file mode 100644 index 0000000000..351c33ecc0 --- /dev/null +++ b/java-streams/pom.xml @@ -0,0 +1,120 @@ + + 4.0.0 + com.baeldung + java-streams + 0.1.0-SNAPSHOT + jar + java-streams + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + log4j + log4j + ${log4j.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + + org.assertj + assertj-core + ${assertj.version} + test + + + com.codepoetics + protonpack + ${protonpack.version} + + + io.vavr + vavr + ${vavr.version} + + + one.util + streamex + ${streamex.version} + + + org.aspectj + aspectjrt + ${asspectj.version} + + + org.aspectj + aspectjweaver + ${asspectj.version} + + + + + java-streams + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + prepare-package + + copy-dependencies + + + ${project.build.directory}/libs + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + -parameters + + + + + + + + 3.5 + 1.16.12 + 0.9.0 + 1.13 + 0.6.5 + 2.10 + + 3.6.1 + 1.8.9 + + diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java b/java-streams/src/main/java/com/baeldung/java_8_features/Detail.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java rename to java-streams/src/main/java/com/baeldung/java_8_features/Detail.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/InfiniteStreams.java b/java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/InfiniteStreams.java rename to java-streams/src/main/java/com/baeldung/stream/InfiniteStreams.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/PrimitiveStreams.java b/java-streams/src/main/java/com/baeldung/stream/PrimitiveStreams.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/PrimitiveStreams.java rename to java-streams/src/main/java/com/baeldung/stream/PrimitiveStreams.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/Product.java b/java-streams/src/main/java/com/baeldung/stream/Product.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/Product.java rename to java-streams/src/main/java/com/baeldung/stream/Product.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/StreamApi.java b/java-streams/src/main/java/com/baeldung/stream/StreamApi.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/StreamApi.java rename to java-streams/src/main/java/com/baeldung/stream/StreamApi.java diff --git a/core-java-8/src/main/java/com/baeldung/stream/StreamIndices.java b/java-streams/src/main/java/com/baeldung/stream/StreamIndices.java similarity index 100% rename from core-java-8/src/main/java/com/baeldung/stream/StreamIndices.java rename to java-streams/src/main/java/com/baeldung/stream/StreamIndices.java diff --git a/java-streams/src/main/resources/logback.xml b/java-streams/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-streams/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java b/java-streams/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java rename to java-streams/src/test/java/com/baeldung/java/conversion/IterableStreamConversionUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java b/java-streams/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java rename to java-streams/src/test/java/com/baeldung/java8/Java8FindAnyFindFirstUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java b/java-streams/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java rename to java-streams/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java b/java-streams/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java rename to java-streams/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/InfiniteStreamUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/PrimitiveStreamsUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamAddUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamAddUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/StreamAddUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/StreamAddUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamApiUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/StreamApiUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/StreamApiUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/StreamIndicesUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/StreamToImmutableUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java rename to java-streams/src/test/java/com/baeldung/stream/SupplierStreamUnitTest.java diff --git a/core-java-8/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java b/java-streams/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java similarity index 100% rename from core-java-8/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java rename to java-streams/src/test/java/com/baeldung/stream/mycollectors/MyImmutableListCollector.java diff --git a/java-streams/src/test/resources/.gitignore b/java-streams/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/java-streams/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/pom.xml b/pom.xml index 080c288987..7ff1aa7d47 100644 --- a/pom.xml +++ b/pom.xml @@ -348,6 +348,7 @@ core-java-collections core-java-io core-java-8 + java-streams core-java-persistence core-kotlin core-groovy @@ -902,6 +903,7 @@ core-java-collections core-java-io core-java-8 + java-streams core-groovy couchbase diff --git a/testing-modules/streams-ordering/pom.xml b/testing-modules/streams-ordering/pom.xml new file mode 100644 index 0000000000..99d08e19be --- /dev/null +++ b/testing-modules/streams-ordering/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + + com.baeldung + StreamsOrdering + 1.0-SNAPSHOT + + + + junit + junit + 4.12 + test + + + + + org.openjdk.jmh + jmh-core + 1.21 + + + + org.openjdk.jmh + jmh-generator-annprocess + 1.21 + provided + + + + \ No newline at end of file diff --git a/testing-modules/streams-ordering/src/test/java/StreamsOrderingTest.java b/testing-modules/streams-ordering/src/test/java/StreamsOrderingTest.java new file mode 100644 index 0000000000..b657911780 --- /dev/null +++ b/testing-modules/streams-ordering/src/test/java/StreamsOrderingTest.java @@ -0,0 +1,148 @@ +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 StreamsOrderingTest { + + Logger logger = Logger.getLogger( StreamsOrderingTest.class.getName()); + + @Before + public void setUp() throws Exception { + logger.setLevel(Level.ALL); + } + + @Test + public void givenTwoCollections_whenStreamed_thenCheckOutputDifferent(){ + + List list = Arrays.asList("B", "A", "C", "D", "F"); + Set 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 list = Arrays.asList("B", "A", "C", "D", "F"); + Set 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 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 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 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 list = Arrays.asList("B", "A", "C", "D", "F"); + + List collectionList = list.stream().parallel().collect(Collectors.toList()); + Set 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 list = Arrays.asList("A", "BB", "CCC"); + + Map 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 list = Arrays.asList("A", "BB", "CCC", "CCC"); + + Map 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)); + } + +} diff --git a/testing-modules/streams-ordering/src/test/java/benchmarking/TestBenchmark.java b/testing-modules/streams-ordering/src/test/java/benchmarking/TestBenchmark.java new file mode 100644 index 0000000000..a3e99e6465 --- /dev/null +++ b/testing-modules/streams-ordering/src/test/java/benchmarking/TestBenchmark.java @@ -0,0 +1,97 @@ +package benchmarking; + +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 TestBenchmark +{ + + @Test + 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 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 list = state.list; + + for (int i = 0; i < 1000; i++) + bh.consume (list.get (i)); + } +} \ No newline at end of file