Merge branch 'master' into bael-16656
This commit is contained in:
commit
f1e8f73aa3
Binary file not shown.
Before Width: | Height: | Size: 9.4 KiB After Width: | Height: | Size: 10 KiB |
|
@ -16,4 +16,6 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||||
- [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency)
|
- [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency)
|
||||||
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
|
- [Interpolation Search in Java](https://www.baeldung.com/java-interpolation-search)
|
||||||
- [The K-Means Clustering Algorithm in Java](https://www.baeldung.com/java-k-means-clustering-algorithm)
|
- [The K-Means Clustering Algorithm in Java](https://www.baeldung.com/java-k-means-clustering-algorithm)
|
||||||
|
- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)
|
||||||
|
- [Breadth-First Search Algorithm in Java](https://www.baeldung.com/java-breadth-first-search)
|
||||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-2) [[next -->]](/algorithms-miscellaneous-4)
|
- More articles: [[<-- prev]](/algorithms-miscellaneous-2) [[next -->]](/algorithms-miscellaneous-4)
|
||||||
|
|
|
@ -1,7 +1,6 @@
|
||||||
## Algorithms - Miscellaneous
|
## Algorithms - Miscellaneous
|
||||||
|
|
||||||
This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](/../algorithms-sorting) and
|
This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](https://github.com/eugenp/tutorials/blob/algorithms-sorting) and [genetic algorithms](https://github.com/eugenp/tutorials/blob/algorithms-genetic), have their own dedicated modules.
|
||||||
[genetic algorithms](/../algorithms-genetic), have their own dedicated modules.
|
|
||||||
|
|
||||||
### Relevant articles:
|
### Relevant articles:
|
||||||
|
|
||||||
|
@ -12,4 +11,4 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||||
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
|
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
|
||||||
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
||||||
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
|
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
|
||||||
- More articles: [[<-- prev]](/../algorithms-miscellaneous-3) [[next -->]](/../algorithms-miscellaneous-5)
|
- More articles: [[<-- prev]](/algorithms-miscellaneous-3) [[next -->]](/algorithms-miscellaneous-5)
|
||||||
|
|
|
@ -8,4 +8,5 @@ This module contains articles about algorithms. Some classes of algorithms, e.g.
|
||||||
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
|
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
|
||||||
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
|
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
|
||||||
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
|
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
|
||||||
|
- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack)
|
||||||
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4)
|
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4)
|
||||||
|
|
|
@ -0,0 +1,33 @@
|
||||||
|
package com.baeldung.algorithms.balancedbinarytree;
|
||||||
|
|
||||||
|
public class BalancedBinaryTree {
|
||||||
|
|
||||||
|
public static boolean isBalanced(Tree tree) {
|
||||||
|
return isBalancedRecursive(tree, -1).isBalanced;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Result isBalancedRecursive(Tree tree, int depth) {
|
||||||
|
if (tree == null) {
|
||||||
|
return new Result(true, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
Result leftSubtreeResult = isBalancedRecursive(tree.left(), depth + 1);
|
||||||
|
Result rightSubtreeResult = isBalancedRecursive(tree.right(), depth + 1);
|
||||||
|
|
||||||
|
boolean isBalanced = Math.abs(leftSubtreeResult.height - rightSubtreeResult.height) <= 1;
|
||||||
|
boolean subtreesAreBalanced = leftSubtreeResult.isBalanced && rightSubtreeResult.isBalanced;
|
||||||
|
int height = Math.max(leftSubtreeResult.height, rightSubtreeResult.height) + 1;
|
||||||
|
|
||||||
|
return new Result(isBalanced && subtreesAreBalanced, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static final class Result {
|
||||||
|
private final boolean isBalanced;
|
||||||
|
private final int height;
|
||||||
|
|
||||||
|
private Result(boolean isBalanced, int height) {
|
||||||
|
this.isBalanced = isBalanced;
|
||||||
|
this.height = height;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.algorithms.balancedbinarytree;
|
||||||
|
|
||||||
|
public class Tree {
|
||||||
|
private final int value;
|
||||||
|
private final Tree left;
|
||||||
|
private final Tree right;
|
||||||
|
|
||||||
|
public Tree(int value, Tree left, Tree right) {
|
||||||
|
this.value = value;
|
||||||
|
this.left = left;
|
||||||
|
this.right = right;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int value() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Tree left() {
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Tree right() {
|
||||||
|
return right;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return String.format("[%s, %s, %s]",
|
||||||
|
value,
|
||||||
|
left == null ? "null" : left.toString(),
|
||||||
|
right == null ? "null" : right.toString()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.algorithms.balancedbinarytree;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
|
||||||
|
public class BalancedBinaryTreeUnitTest extends BinaryTreeDataProvider {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBalancedTrees_whenCallingIsBalanced_ShouldReturnTrue() {
|
||||||
|
for (Tree tree : balancedTrees()) {
|
||||||
|
assertTrue(toString(tree) + " should be balanced", BalancedBinaryTree.isBalanced(tree));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUnbalancedTrees_whenCallingIsBalanced_ShouldReturnFalse() {
|
||||||
|
for (Tree tree : unbalancedTrees()) {
|
||||||
|
assertFalse(toString(tree) + " should not be balanced", BalancedBinaryTree.isBalanced(tree));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String toString(Tree tree) {
|
||||||
|
return tree != null ? tree.toString() : "null";
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,69 @@
|
||||||
|
package com.baeldung.algorithms.balancedbinarytree;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collection;
|
||||||
|
|
||||||
|
class BinaryTreeDataProvider {
|
||||||
|
|
||||||
|
static Collection<Tree> balancedTrees() {
|
||||||
|
return Arrays.asList(
|
||||||
|
null,
|
||||||
|
leaf(1),
|
||||||
|
tree(1, leaf(2), leaf(3)),
|
||||||
|
tree(
|
||||||
|
1,
|
||||||
|
leaf(2),
|
||||||
|
tree(3, leaf(4), null)
|
||||||
|
),
|
||||||
|
tree(
|
||||||
|
1,
|
||||||
|
tree(
|
||||||
|
2,
|
||||||
|
tree(3, leaf(4), null),
|
||||||
|
leaf(5)
|
||||||
|
),
|
||||||
|
tree(
|
||||||
|
6,
|
||||||
|
leaf(7),
|
||||||
|
tree(8, null, leaf(9))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static Collection<Tree> unbalancedTrees() {
|
||||||
|
return Arrays.asList(
|
||||||
|
tree(
|
||||||
|
1,
|
||||||
|
tree(2, leaf(3), null),
|
||||||
|
null
|
||||||
|
),
|
||||||
|
tree(
|
||||||
|
1,
|
||||||
|
tree(
|
||||||
|
2,
|
||||||
|
tree(3, leaf(4), leaf(5)),
|
||||||
|
null
|
||||||
|
),
|
||||||
|
tree(6, leaf(7), null)
|
||||||
|
),
|
||||||
|
tree(
|
||||||
|
1,
|
||||||
|
tree(2, leaf(3), null),
|
||||||
|
tree(
|
||||||
|
4,
|
||||||
|
tree(5, leaf(6), leaf(7)),
|
||||||
|
null
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Tree leaf(int value) {
|
||||||
|
return new Tree(value, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Tree tree(int value, Tree left, Tree right) {
|
||||||
|
return new Tree(value, left, right);
|
||||||
|
}
|
||||||
|
}
|
|
@ -17,3 +17,4 @@ This module contains articles about sorting algorithms.
|
||||||
- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers)
|
- [Sorting Strings by Contained Numbers in Java](https://www.baeldung.com/java-sort-strings-contained-numbers)
|
||||||
- [Radix Sort in Java](https://www.baeldung.com/java-radix-sort)
|
- [Radix Sort in Java](https://www.baeldung.com/java-radix-sort)
|
||||||
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
|
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
|
||||||
|
- [Bucket Sort in Java](https://www.baeldung.com/java-bucket-sort)
|
||||||
|
|
|
@ -12,10 +12,16 @@
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.auto.value</groupId>
|
||||||
|
<artifactId>auto-value-annotations</artifactId>
|
||||||
|
<version>${auto-value.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.auto.value</groupId>
|
<groupId>com.google.auto.value</groupId>
|
||||||
<artifactId>auto-value</artifactId>
|
<artifactId>auto-value</artifactId>
|
||||||
<version>${auto-value.version}</version>
|
<version>${auto-value.version}</version>
|
||||||
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.auto.factory</groupId>
|
<groupId>com.google.auto.factory</groupId>
|
||||||
|
@ -43,9 +49,9 @@
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<auto-value.version>1.3</auto-value.version>
|
<auto-value.version>1.6.6</auto-value.version>
|
||||||
<auto-factory.version>1.0-beta5</auto-factory.version>
|
<auto-factory.version>1.0-beta6</auto-factory.version>
|
||||||
<auto-service.version>1.0-rc5</auto-service.version>
|
<auto-service.version>1.0-rc6</auto-service.version>
|
||||||
<guice.version>4.2.0</guice.version>
|
<guice.version>4.2.0</guice.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,38 @@
|
||||||
|
package com.baeldung.autovalue;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.google.auto.value.AutoValue;
|
||||||
|
|
||||||
|
@AutoValue
|
||||||
|
public abstract class Person {
|
||||||
|
|
||||||
|
public abstract String name();
|
||||||
|
|
||||||
|
public abstract List<String> favoriteMovies();
|
||||||
|
|
||||||
|
public static Builder builder() {
|
||||||
|
return new AutoValue_Person.Builder();
|
||||||
|
}
|
||||||
|
|
||||||
|
@AutoValue.Builder
|
||||||
|
public static abstract class Builder {
|
||||||
|
|
||||||
|
public abstract Builder name(String value);
|
||||||
|
|
||||||
|
public abstract Builder favoriteMovies(List<String> value);
|
||||||
|
|
||||||
|
abstract List<String> favoriteMovies();
|
||||||
|
|
||||||
|
abstract Person autoBuild();
|
||||||
|
|
||||||
|
public Person build() {
|
||||||
|
List<String> favoriteMovies = favoriteMovies();
|
||||||
|
List<String> copy = Collections.unmodifiableList(new ArrayList<>(favoriteMovies));
|
||||||
|
favoriteMovies(copy);
|
||||||
|
return autoBuild();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,37 @@
|
||||||
|
package com.baeldung.autovalue;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit Test which verifies that the {@link Person} value object creates defensive copies of its favoriteMovies list.
|
||||||
|
*/
|
||||||
|
public class PersonUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNewPerson_whenModifyOriginalList_thenValueObjectIsNotAlsoModified() {
|
||||||
|
// GIVEN new Person
|
||||||
|
List<String> originalFavoriteMoviesList = new ArrayList<String>();
|
||||||
|
originalFavoriteMoviesList.add("Training Day");
|
||||||
|
originalFavoriteMoviesList.add("Fast and the Furious");
|
||||||
|
Person person = Person.builder()
|
||||||
|
.name("Dan")
|
||||||
|
.favoriteMovies(originalFavoriteMoviesList)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
// WHEN modify original list
|
||||||
|
originalFavoriteMoviesList.add("Friday");
|
||||||
|
|
||||||
|
// THEN Person remains unaffected
|
||||||
|
assertFalse(person.favoriteMovies()
|
||||||
|
.contains("Friday"));
|
||||||
|
assertEquals(2, person.favoriteMovies()
|
||||||
|
.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -12,4 +12,5 @@ This module contains articles about core Groovy concepts
|
||||||
- [Concatenate Strings with Groovy](https://www.baeldung.com/groovy-concatenate-strings)
|
- [Concatenate Strings with Groovy](https://www.baeldung.com/groovy-concatenate-strings)
|
||||||
- [Metaprogramming in Groovy](https://www.baeldung.com/groovy-metaprogramming)
|
- [Metaprogramming in Groovy](https://www.baeldung.com/groovy-metaprogramming)
|
||||||
- [A Quick Guide to Working with Web Services in Groovy](https://www.baeldung.com/groovy-web-services)
|
- [A Quick Guide to Working with Web Services in Groovy](https://www.baeldung.com/groovy-web-services)
|
||||||
|
- [Categories in Groovy](https://www.baeldung.com/groovy-categories)
|
||||||
- [[<-- Prev]](/core-groovy)
|
- [[<-- Prev]](/core-groovy)
|
||||||
|
|
|
@ -0,0 +1,6 @@
|
||||||
|
## Core Java 9 streams
|
||||||
|
|
||||||
|
This module contains articles about Java 9 streams
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach)
|
|
@ -0,0 +1,31 @@
|
||||||
|
<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-9-streams</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<name>core-java-9-streams</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-java</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-java</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-9-streams</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
</properties>
|
||||||
|
</project>
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.breakforeach;
|
package com.baeldung.streams.breakforeach;
|
||||||
|
|
||||||
import java.util.Spliterator;
|
import java.util.Spliterator;
|
||||||
import java.util.function.BiConsumer;
|
import java.util.function.BiConsumer;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.breakforeach;
|
package com.baeldung.streams.breakforeach;
|
||||||
|
|
||||||
import java.util.Spliterator;
|
import java.util.Spliterator;
|
||||||
import java.util.Spliterators;
|
import java.util.Spliterators;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.breakforeach;
|
package com.baeldung.streams.breakforeach;
|
||||||
|
|
||||||
import java.util.function.Predicate;
|
import java.util.function.Predicate;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.breakforeach;
|
package com.baeldung.streams.breakforeach;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.breakforeach;
|
package com.baeldung.streams.breakforeach;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
|
@ -8,4 +8,5 @@
|
||||||
- [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs)
|
- [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs)
|
||||||
- [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated)
|
- [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated)
|
||||||
- [Overview of Java Built-in Annotations](https://www.baeldung.com/java-default-annotations)
|
- [Overview of Java Built-in Annotations](https://www.baeldung.com/java-default-annotations)
|
||||||
- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)
|
- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)
|
||||||
|
- [Efficient Word Frequency Calculator in Java](https://www.baeldung.com/java-word-frequency)
|
||||||
|
|
|
@ -12,4 +12,5 @@ This module contains articles about Java arrays
|
||||||
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
|
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
|
||||||
- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element)
|
- [Removing an Element from an Array in Java](https://www.baeldung.com/java-array-remove-element)
|
||||||
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
|
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
|
||||||
|
- [Adding an Element to a Java Array vs an ArrayList](https://www.baeldung.com/java-add-element-to-array-vs-list)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-arrays)
|
- [[<-- Prev]](/core-java-modules/core-java-arrays)
|
||||||
|
|
|
@ -12,4 +12,4 @@
|
||||||
- [Sorting in Java](https://www.baeldung.com/java-sorting)
|
- [Sorting in Java](https://www.baeldung.com/java-sorting)
|
||||||
- [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size)
|
- [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size)
|
||||||
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
|
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
|
||||||
|
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
||||||
|
|
|
@ -11,4 +11,5 @@ This module contains articles about the Java List collection
|
||||||
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
|
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
|
||||||
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
|
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
|
||||||
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
|
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-collections-list)[[Next -->]](/core-java-modules/core-java-collections-list-3)
|
- [Searching for a String in an ArrayList](https://www.baeldung.com/java-search-string-arraylist)
|
||||||
|
- [[<-- Prev]](/core-java-modules/core-java-collections-list)[[Next -->]](/core-java-modules/core-java-collections-list-3)
|
||||||
|
|
|
@ -0,0 +1,17 @@
|
||||||
|
<?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-date-operations</artifactId>
|
||||||
|
<version>${project.parent.version}</version>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-java</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-java</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,15 @@
|
||||||
|
package com.baeldung.datetime;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
public class CalendarUtils {
|
||||||
|
|
||||||
|
public static Calendar getPlusDays(Date date, int amount) throws ParseException {
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.setTime(date);
|
||||||
|
calendar.add(Calendar.DAY_OF_YEAR, amount);
|
||||||
|
return calendar;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.datetime;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
public class DateUtils {
|
||||||
|
|
||||||
|
public static Date getNow() {
|
||||||
|
return new Date();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Date getDate(long millis) {
|
||||||
|
return new Date(millis);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Date getDate(String dateAsString, String pattern) throws ParseException {
|
||||||
|
return new SimpleDateFormat(pattern).parse(dateAsString);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.datetime.sql;
|
||||||
|
|
||||||
|
import java.sql.Date;
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
|
||||||
|
public class DateUtils {
|
||||||
|
|
||||||
|
public static Date getNow() {
|
||||||
|
return new Date(System.currentTimeMillis());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Date getDate(String dateAsString) {
|
||||||
|
return Date.valueOf(dateAsString);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Date getDate(String dateAsString, String pattern) throws ParseException {
|
||||||
|
java.util.Date customUtilDate = new SimpleDateFormat(pattern).parse(dateAsString);
|
||||||
|
return new Date(customUtilDate.getTime());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.datetime.sql;
|
||||||
|
|
||||||
|
import java.sql.Time;
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
|
||||||
|
public class TimeUtils {
|
||||||
|
|
||||||
|
public static Time getNow() {
|
||||||
|
return new Time(System.currentTimeMillis());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Time getTime(String timeAsString) {
|
||||||
|
return Time.valueOf(timeAsString);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Time getTime(String dateAsString, String pattern) throws ParseException {
|
||||||
|
java.util.Date customUtilDate = new SimpleDateFormat(pattern).parse(dateAsString);
|
||||||
|
return new Time(customUtilDate.getTime());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.datetime.sql;
|
||||||
|
|
||||||
|
import java.sql.Timestamp;
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
|
||||||
|
public class TimestampUtils {
|
||||||
|
|
||||||
|
public static Timestamp getNow() {
|
||||||
|
return new Timestamp(System.currentTimeMillis());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Timestamp getTimestamp(String timestampAsString) {
|
||||||
|
return Timestamp.valueOf(timestampAsString);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Timestamp getTimestamp(String dateAsString, String pattern) throws ParseException {
|
||||||
|
java.util.Date customUtilDate = new SimpleDateFormat(pattern).parse(dateAsString);
|
||||||
|
return new Timestamp(customUtilDate.getTime());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.datetime;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.datetime.CalendarUtils;
|
||||||
|
import com.baeldung.datetime.DateUtils;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
public class CalendarUtilsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDateAndDaysToAdd_thenCalendarIsCorrectlyReturned() throws ParseException {
|
||||||
|
Date initialDate = DateUtils.getDate("2020/01/01", "yyyy/MM/dd");
|
||||||
|
Date expectedDate= DateUtils.getDate("2020/01/11", "yyyy/MM/dd");
|
||||||
|
assertEquals(expectedDate, CalendarUtils.getPlusDays(initialDate, 10).getTime());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.datetime;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.datetime.DateUtils;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
public class DateUtilsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTimeMillis_thenDateIsReturned() {
|
||||||
|
Date now = DateUtils.getNow();
|
||||||
|
assertEquals(DateUtils.getDate(now.getTime()), now);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDateAndPattern_thenDateIsCorrectlyReturned() throws ParseException {
|
||||||
|
long milliseconds = new Date(2020 - 1900, 0, 1).getTime();
|
||||||
|
assertEquals(DateUtils.getDate(milliseconds), DateUtils.getDate("2020/01/01", "yyyy/MM/dd"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.datetime.sql;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.datetime.sql.DateUtils;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
public class DateUtilsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCurrentDate_thenTodayIsReturned() {
|
||||||
|
assertEquals(DateUtils.getNow(), new Date());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
public void givenDateAsString_whenPatternIsNotRespected_thenExceptionIsThrown() {
|
||||||
|
DateUtils.getDate("2020 01 01");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDateAndPattern_thenDateIsCorrectlyReturned() throws ParseException {
|
||||||
|
assertEquals(DateUtils.getDate("2020-01-01"), DateUtils.getDate("2020/01/01", "yyyy/MM/dd"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package com.baeldung.datetime.sql;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.datetime.sql.TimeUtils;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
public class TimeUtilsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCurrentTime_thenNowIsReturned() {
|
||||||
|
assertEquals(TimeUtils.getNow(), new Date());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
public void givenTimeAsString_whenPatternIsNotRespected_thenExceptionIsThrown() {
|
||||||
|
TimeUtils.getTime("10 11 12");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTimeAndPattern_thenTimeIsCorrectlyReturned() throws ParseException {
|
||||||
|
assertEquals(TimeUtils.getTime("10:11:12"), TimeUtils.getTime("10 11 12", "hh mm ss"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,29 @@
|
||||||
|
package com.baeldung.datetime.sql;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.datetime.sql.TimestampUtils;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
public class TimestampUtilsUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCurrentTimestamp_thenNowIsReturned() {
|
||||||
|
assertEquals(TimestampUtils.getNow()
|
||||||
|
.getTime(), new Date().getTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalArgumentException.class)
|
||||||
|
public void givenTimestampAsString_whenPatternIsNotRespected_thenExceptionIsThrown() {
|
||||||
|
TimestampUtils.getTimestamp("2020/01/01 10:11-12");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTimestampAndPattern_thenTimestampIsCorrectlyReturned() throws ParseException {
|
||||||
|
assertEquals(TimestampUtils.getTimestamp("2020-01-01 10:11:12"), TimestampUtils.getTimestamp("2020/01/01 10:11-12", "yyyy/MM/dd hh:mm-ss"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.random;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
public class LegacyRandomDateTimes {
|
||||||
|
|
||||||
|
public static Date between(Date startInclusive, Date endExclusive) {
|
||||||
|
long startMillis = startInclusive.getTime();
|
||||||
|
long endMillis = endExclusive.getTime();
|
||||||
|
long randomMillisSinceEpoch = ThreadLocalRandom.current().nextLong(startMillis, endMillis);
|
||||||
|
|
||||||
|
return new Date(randomMillisSinceEpoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Date timestamp() {
|
||||||
|
return new Date(ThreadLocalRandom.current().nextInt() * 1000L);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.random;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
public class RandomDateTimes {
|
||||||
|
|
||||||
|
public static Instant timestamp() {
|
||||||
|
return Instant.ofEpochSecond(ThreadLocalRandom.current().nextInt());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Instant between(Instant startInclusive, Instant endExclusive) {
|
||||||
|
long startSeconds = startInclusive.getEpochSecond();
|
||||||
|
long endSeconds = endExclusive.getEpochSecond();
|
||||||
|
long random = ThreadLocalRandom.current().nextLong(startSeconds, endSeconds);
|
||||||
|
|
||||||
|
return Instant.ofEpochSecond(random);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Instant after(Instant startInclusive) {
|
||||||
|
return between(startInclusive, Instant.MAX);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Instant before(Instant upperExclusive) {
|
||||||
|
return between(Instant.MIN, upperExclusive);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.random;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
public class RandomDates {
|
||||||
|
|
||||||
|
public static LocalDate between(LocalDate startInclusive, LocalDate endExclusive) {
|
||||||
|
long startEpochDay = startInclusive.toEpochDay();
|
||||||
|
long endEpochDay = endExclusive.toEpochDay();
|
||||||
|
long randomDay = ThreadLocalRandom.current().nextLong(startEpochDay, endEpochDay);
|
||||||
|
|
||||||
|
return LocalDate.ofEpochDay(randomDay);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalDate date() {
|
||||||
|
int hundredYears = 100 * 365;
|
||||||
|
return LocalDate.ofEpochDay(ThreadLocalRandom.current().nextInt(-hundredYears, hundredYears));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.random;
|
||||||
|
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
public class RandomTimes {
|
||||||
|
|
||||||
|
public static LocalTime between(LocalTime startTime, LocalTime endTime) {
|
||||||
|
int startSeconds = startTime.toSecondOfDay();
|
||||||
|
int endSeconds = endTime.toSecondOfDay();
|
||||||
|
int randomTime = ThreadLocalRandom.current().nextInt(startSeconds, endSeconds);
|
||||||
|
|
||||||
|
return LocalTime.ofSecondOfDay(randomTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalTime time() {
|
||||||
|
return between(LocalTime.MIN, LocalTime.MAX);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,36 @@
|
||||||
|
package com.baeldung.random;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.RepeatedTest;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
class LegacyRandomDateTimesUnitTest {
|
||||||
|
|
||||||
|
private static final Date MIN_DATE = new Date(Long.MIN_VALUE);
|
||||||
|
private static final Date MAX_DATE = new Date(Long.MAX_VALUE);
|
||||||
|
|
||||||
|
@RepeatedTest(100)
|
||||||
|
void givenARange_WhenGenTimestamp_ShouldBeInRange() {
|
||||||
|
long aDay = TimeUnit.DAYS.toMillis(1);
|
||||||
|
long now = new Date().getTime();
|
||||||
|
|
||||||
|
Date hundredYearsAgo = new Date(now - aDay * 365 * 100);
|
||||||
|
Date tenDaysAgo = new Date(now - aDay * 10);
|
||||||
|
|
||||||
|
Date random = LegacyRandomDateTimes.between(hundredYearsAgo, tenDaysAgo);
|
||||||
|
assertThat(random).isBetween(hundredYearsAgo, tenDaysAgo);
|
||||||
|
}
|
||||||
|
|
||||||
|
@RepeatedTest(100)
|
||||||
|
void givenNoRange_WhenGenTimestamp_ShouldGenerateRandomTimestamps() {
|
||||||
|
Date random = LegacyRandomDateTimes.timestamp();
|
||||||
|
|
||||||
|
assertThat(random)
|
||||||
|
.isNotNull()
|
||||||
|
.isBetween(MIN_DATE, MAX_DATE);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.random;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.RepeatedTest;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.Instant;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
class RandomDateTimesUnitTest {
|
||||||
|
|
||||||
|
@RepeatedTest(100)
|
||||||
|
void givenNoRange_WhenGenTimestamp_ShouldGenerateRandomTimestamps() {
|
||||||
|
Instant random = RandomDateTimes.timestamp();
|
||||||
|
|
||||||
|
assertThat(random).isBetween(Instant.MIN, Instant.MAX);
|
||||||
|
}
|
||||||
|
|
||||||
|
@RepeatedTest(100)
|
||||||
|
void givenARange_WhenGenTimestamp_ShouldBeInRange() {
|
||||||
|
Instant hundredYearsAgo = Instant.now().minus(Duration.ofDays(100 * 365));
|
||||||
|
Instant tenDaysAgo = Instant.now().minus(Duration.ofDays(10));
|
||||||
|
|
||||||
|
Instant random = RandomDateTimes.between(hundredYearsAgo, tenDaysAgo);
|
||||||
|
assertThat(random).isBetween(hundredYearsAgo, tenDaysAgo);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,27 @@
|
||||||
|
package com.baeldung.random;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.RepeatedTest;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.Month;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
class RandomDatesUnitTest {
|
||||||
|
|
||||||
|
@RepeatedTest(100)
|
||||||
|
void givenNoRange_WhenGenDate_ShouldGenerateRandomDates() {
|
||||||
|
LocalDate randomDay = RandomDates.date();
|
||||||
|
|
||||||
|
assertThat(randomDay).isAfter(LocalDate.MIN).isBefore(LocalDate.MAX);
|
||||||
|
}
|
||||||
|
|
||||||
|
@RepeatedTest(100)
|
||||||
|
void givenARange_WhenGenDate_ShouldBeInRange() {
|
||||||
|
LocalDate start = LocalDate.of(1989, Month.OCTOBER, 14);
|
||||||
|
LocalDate end = LocalDate.now();
|
||||||
|
|
||||||
|
LocalDate random = RandomDates.between(start, end);
|
||||||
|
assertThat(random).isAfter(start).isBefore(end);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,20 @@
|
||||||
|
package com.baeldung.random;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.RepeatedTest;
|
||||||
|
|
||||||
|
import java.time.LocalTime;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
class RandomTimesUnitTest {
|
||||||
|
|
||||||
|
@RepeatedTest(100)
|
||||||
|
void givenARange_WhenGenTime_ShouldBeInRange() {
|
||||||
|
LocalTime morning = LocalTime.of(8, 30);
|
||||||
|
LocalTime randomTime = RandomTimes.between(LocalTime.MIDNIGHT, morning);
|
||||||
|
|
||||||
|
assertThat(randomTime)
|
||||||
|
.isAfter(LocalTime.MIDNIGHT).isBefore(morning)
|
||||||
|
.isAfter(LocalTime.MIN).isBefore(LocalTime.MAX);
|
||||||
|
}
|
||||||
|
}
|
|
@ -12,4 +12,8 @@ This module contains articles about core java exceptions
|
||||||
- [“Sneaky Throws” in Java](https://www.baeldung.com/java-sneaky-throws)
|
- [“Sneaky Throws” in Java](https://www.baeldung.com/java-sneaky-throws)
|
||||||
- [The StackOverflowError in Java](https://www.baeldung.com/java-stack-overflow-error)
|
- [The StackOverflowError in Java](https://www.baeldung.com/java-stack-overflow-error)
|
||||||
- [Checked and Unchecked Exceptions in Java](https://www.baeldung.com/java-checked-unchecked-exceptions)
|
- [Checked and Unchecked Exceptions in Java](https://www.baeldung.com/java-checked-unchecked-exceptions)
|
||||||
|
- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources)
|
||||||
|
- [Java Global Exception Handler](https://www.baeldung.com/java-global-exception-handler)
|
||||||
|
- [Common Java Exceptions](https://www.baeldung.com/java-common-exceptions)
|
||||||
|
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
||||||
|
- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
|
||||||
|
|
|
@ -0,0 +1,16 @@
|
||||||
|
package com.baeldung.trywithresource;
|
||||||
|
|
||||||
|
public class AutoCloseableMain {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
orderOfClosingResources();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void orderOfClosingResources() throws Exception {
|
||||||
|
try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst();
|
||||||
|
AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {
|
||||||
|
af.doSomething();
|
||||||
|
as.doSomething();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.trywithresource;
|
||||||
|
|
||||||
|
public class AutoCloseableResourcesFirst implements AutoCloseable {
|
||||||
|
|
||||||
|
public AutoCloseableResourcesFirst() {
|
||||||
|
System.out.println("Constructor -> AutoCloseableResources_First");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void doSomething() {
|
||||||
|
System.out.println("Something -> AutoCloseableResources_First");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() throws Exception {
|
||||||
|
System.out.println("Closed AutoCloseableResources_First");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,17 @@
|
||||||
|
package com.baeldung.trywithresource;
|
||||||
|
|
||||||
|
public class AutoCloseableResourcesSecond implements AutoCloseable {
|
||||||
|
|
||||||
|
public AutoCloseableResourcesSecond() {
|
||||||
|
System.out.println("Constructor -> AutoCloseableResources_Second");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void doSomething() {
|
||||||
|
System.out.println("Something -> AutoCloseableResources_Second");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() throws Exception {
|
||||||
|
System.out.println("Closed AutoCloseableResources_Second");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,8 @@
|
||||||
|
package com.baeldung.trywithresource;
|
||||||
|
|
||||||
|
public class MyResource implements AutoCloseable {
|
||||||
|
@Override
|
||||||
|
public void close() throws Exception {
|
||||||
|
System.out.println("Closed MyResource");
|
||||||
|
}
|
||||||
|
}
|
|
@ -3,4 +3,5 @@
|
||||||
|
|
||||||
- [Create a File in a Specific Directory in Java](https://www.baeldung.com/java-create-file-in-directory)
|
- [Create a File in a Specific Directory in Java](https://www.baeldung.com/java-create-file-in-directory)
|
||||||
- [A Guide to the Java FileReader Class](https://www.baeldung.com/java-filereader)
|
- [A Guide to the Java FileReader Class](https://www.baeldung.com/java-filereader)
|
||||||
|
- [The Java File Class](https://www.baeldung.com/java-io-file)
|
||||||
|
- [Java FileWriter](https://www.baeldung.com/java-filewriter)
|
||||||
|
|
|
@ -0,0 +1,96 @@
|
||||||
|
package com.baeldung.scanner;
|
||||||
|
|
||||||
|
import lombok.extern.log4j.Log4j;
|
||||||
|
import org.apache.log4j.LogManager;
|
||||||
|
import org.apache.log4j.PropertyConfigurator;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
@Log4j
|
||||||
|
public class HasNextVsHasNextLineDemo {
|
||||||
|
private static final String LINE = "----------------------------";
|
||||||
|
private static final String END_LINE = "--------OUTPUT--END---------\n";
|
||||||
|
|
||||||
|
|
||||||
|
private static final String INPUT = new StringBuilder()
|
||||||
|
.append("magic\tproject\n")
|
||||||
|
.append(" database: oracle\n")
|
||||||
|
.append("dependencies:\n")
|
||||||
|
.append("spring:foo:bar\n")
|
||||||
|
.append("\n").toString();
|
||||||
|
|
||||||
|
private static void hasNextBasic() {
|
||||||
|
printHeader("hasNext() Basic");
|
||||||
|
Scanner scanner = new Scanner(INPUT);
|
||||||
|
while (scanner.hasNext()) {
|
||||||
|
log.info(scanner.next());
|
||||||
|
}
|
||||||
|
log.info(END_LINE);
|
||||||
|
scanner.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void hasNextWithDelimiter() {
|
||||||
|
printHeader("hasNext() with delimiter");
|
||||||
|
Scanner scanner = new Scanner(INPUT);
|
||||||
|
while (scanner.hasNext()) {
|
||||||
|
String token = scanner.next();
|
||||||
|
if ("dependencies:".equals(token)) {
|
||||||
|
scanner.useDelimiter(":");
|
||||||
|
}
|
||||||
|
log.info(token);
|
||||||
|
}
|
||||||
|
log.info(END_LINE);
|
||||||
|
scanner.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void hasNextWithDelimiterFixed() {
|
||||||
|
printHeader("hasNext() with delimiter FIX");
|
||||||
|
Scanner scanner = new Scanner(INPUT);
|
||||||
|
while (scanner.hasNext()) {
|
||||||
|
String token = scanner.next();
|
||||||
|
if ("dependencies:".equals(token)) {
|
||||||
|
scanner.useDelimiter(":|\\s+");
|
||||||
|
}
|
||||||
|
log.info(token);
|
||||||
|
}
|
||||||
|
log.info(END_LINE);
|
||||||
|
scanner.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void addLineNumber() {
|
||||||
|
printHeader("add line number by hasNextLine() ");
|
||||||
|
Scanner scanner = new Scanner(INPUT);
|
||||||
|
int i = 0;
|
||||||
|
while (scanner.hasNextLine()) {
|
||||||
|
log.info(String.format("%d|%s", ++i, scanner.nextLine()));
|
||||||
|
}
|
||||||
|
log.info(END_LINE);
|
||||||
|
scanner.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void printHeader(String title) {
|
||||||
|
log.info(LINE);
|
||||||
|
log.info(title);
|
||||||
|
log.info(LINE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
setLogger();
|
||||||
|
hasNextBasic();
|
||||||
|
hasNextWithDelimiter();
|
||||||
|
hasNextWithDelimiterFixed();
|
||||||
|
addLineNumber();
|
||||||
|
}
|
||||||
|
|
||||||
|
//overwrite the logger config
|
||||||
|
private static void setLogger() throws IOException {
|
||||||
|
InputStream is = HasNextVsHasNextLineDemo.class.getResourceAsStream("/scanner/log4j.properties");
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.load(is);
|
||||||
|
LogManager.resetConfiguration();
|
||||||
|
PropertyConfigurator.configure(props);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,4 @@
|
||||||
|
log4j.rootLogger=INFO, A1
|
||||||
|
log4j.appender.A1=org.apache.log4j.ConsoleAppender
|
||||||
|
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
|
||||||
|
log4j.appender.A1.layout.ConversionPattern=[DEMO]%m%n
|
|
@ -0,0 +1,44 @@
|
||||||
|
package com.baeldung.scanner;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.NoSuchElementException;
|
||||||
|
import java.util.Scanner;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class JavaScannerUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenReadingLines_thenCorrect() {
|
||||||
|
String input = "Scanner\nTest\n";
|
||||||
|
try (Scanner scanner = new Scanner(input)) {
|
||||||
|
assertEquals("Scanner", scanner.nextLine());
|
||||||
|
assertEquals("Test", scanner.nextLine());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenReadingPartialLines_thenCorrect() {
|
||||||
|
String input = "Scanner\n";
|
||||||
|
try (Scanner scanner = new Scanner(input)) {
|
||||||
|
scanner.useDelimiter("");
|
||||||
|
scanner.next();
|
||||||
|
assertEquals("canner", scanner.nextLine());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NoSuchElementException.class)
|
||||||
|
public void givenNoNewLine_whenReadingNextLine_thenThrowNoSuchElementException() {
|
||||||
|
try (Scanner scanner = new Scanner("")) {
|
||||||
|
String result = scanner.nextLine();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = IllegalStateException.class)
|
||||||
|
public void givenScannerIsClosed_whenReadingNextLine_thenThrowIllegalStateException() {
|
||||||
|
Scanner scanner = new Scanner("");
|
||||||
|
scanner.close();
|
||||||
|
String result = scanner.nextLine();
|
||||||
|
}
|
||||||
|
}
|
|
@ -7,11 +7,12 @@ This module contains articles about Object-oriented programming (OOP) in Java
|
||||||
- [Access Modifiers in Java](https://www.baeldung.com/java-access-modifiers)
|
- [Access Modifiers in Java](https://www.baeldung.com/java-access-modifiers)
|
||||||
- [Guide to the super Java Keyword](https://www.baeldung.com/java-super)
|
- [Guide to the super Java Keyword](https://www.baeldung.com/java-super)
|
||||||
- [Guide to the this Java Keyword](https://www.baeldung.com/java-this)
|
- [Guide to the this Java Keyword](https://www.baeldung.com/java-this)
|
||||||
- [Java Public Access Modifier](https://www.baeldung.com/java-public-keyword)
|
- [Java ‘public’ Access Modifier](https://www.baeldung.com/java-public-keyword)
|
||||||
- [Composition, Aggregation and Association in Java](https://www.baeldung.com/java-composition-aggregation-association)
|
- [Composition, Aggregation and Association in Java](https://www.baeldung.com/java-composition-aggregation-association)
|
||||||
- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes)
|
- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes)
|
||||||
- [A Guide to Inner Interfaces in Java](https://www.baeldung.com/java-inner-interfaces)
|
- [A Guide to Inner Interfaces in Java](https://www.baeldung.com/java-inner-interfaces)
|
||||||
- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects)
|
- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects)
|
||||||
- [Java Interfaces](https://www.baeldung.com/java-interfaces)
|
- [Java Interfaces](https://www.baeldung.com/java-interfaces)
|
||||||
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
|
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-lang-oop-2)
|
- [Methods in Java](https://www.baeldung.com/java-methods)
|
||||||
|
- [[<-- Prev]](/core-java-modules/core-java-lang-oop-2)
|
||||||
|
|
|
@ -11,4 +11,5 @@ This module contains articles about Java syntax
|
||||||
- [Java Double Brace Initialization](https://www.baeldung.com/java-double-brace-initialization)
|
- [Java Double Brace Initialization](https://www.baeldung.com/java-double-brace-initialization)
|
||||||
- [The Java Native Keyword and Methods](https://www.baeldung.com/java-native)
|
- [The Java Native Keyword and Methods](https://www.baeldung.com/java-native)
|
||||||
- [Variable Scope in Java](https://www.baeldung.com/java-variable-scope)
|
- [Variable Scope in Java](https://www.baeldung.com/java-variable-scope)
|
||||||
|
- [Java ‘protected’ Access Modifier](https://www.baeldung.com/java-protected-access-modifier)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-lang-syntax)
|
- [[<-- Prev]](/core-java-modules/core-java-lang-syntax)
|
||||||
|
|
|
@ -13,4 +13,7 @@ This module contains articles about core features in the Java language
|
||||||
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
|
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
|
||||||
- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name)
|
- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name)
|
||||||
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
|
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
|
||||||
- [[More --> ]](/core-java-modules/core-java-lang-2)
|
- [The Java continue and break Keywords](https://www.baeldung.com/java-continue-and-break)
|
||||||
|
- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums)
|
||||||
|
- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java)
|
||||||
|
- [[More --> ]](/core-java-modules/core-java-lang-2)
|
||||||
|
|
|
@ -9,4 +9,5 @@ This module contains articles about networking in Java
|
||||||
- [Using Curl in Java](https://www.baeldung.com/java-curl)
|
- [Using Curl in Java](https://www.baeldung.com/java-curl)
|
||||||
- [Do a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
|
- [Do a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
|
||||||
- [Sending Emails with Java](http://www.baeldung.com/java-email)
|
- [Sending Emails with Java](http://www.baeldung.com/java-email)
|
||||||
|
- [Authentication with HttpUrlConnection](https://www.baeldung.com/java-http-url-connection)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-networking)
|
- [[<-- Prev]](/core-java-modules/core-java-networking)
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- [Intro to the Java SecurityManager](https://www.baeldung.com/java-security-manager)
|
|
@ -0,0 +1,16 @@
|
||||||
|
## Core Java streams
|
||||||
|
|
||||||
|
This module contains articles about the Stream API in Java.
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
- [The Java 8 Stream API Tutorial](https://www.baeldung.com/java-8-streams)
|
||||||
|
- [Introduction to Java 8 Streams](https://www.baeldung.com/java-8-streams-introduction)
|
||||||
|
- [Java 8 Stream findFirst() vs. findAny()](https://www.baeldung.com/java-stream-findfirst-vs-findany)
|
||||||
|
- [Guide to Stream.reduce()](https://www.baeldung.com/java-stream-reduce)
|
||||||
|
- [Java IntStream Conversions](https://www.baeldung.com/java-intstream-convert)
|
||||||
|
- [Java 8 Streams peek() API](https://www.baeldung.com/java-streams-peek-api)
|
||||||
|
- [Working With Maps Using Streams](https://www.baeldung.com/java-maps-streams)
|
||||||
|
- [Collect a Java Stream to an Immutable Collection](https://www.baeldung.com/java-stream-immutable-collection)
|
||||||
|
- [How to Add a Single Element to a Stream](https://www.baeldung.com/java-stream-append-prepend)
|
||||||
|
- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
|
||||||
|
- More articles: [[<-- prev>]](/../core-java-streams) [[next -->]](/../core-java-streams-3)
|
|
@ -1,49 +1,53 @@
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?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">
|
<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>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<groupId>com.baeldung.javastreams2</groupId>
|
<artifactId>core-java-streams-2</artifactId>
|
||||||
<artifactId>java-streams-2</artifactId>
|
<version>1.0</version>
|
||||||
<version>1.0</version>
|
<name>core-java-streams-2</name>
|
||||||
<name>java-streams-2</name>
|
<packaging>jar</packaging>
|
||||||
<packaging>jar</packaging>
|
|
||||||
|
<parent>
|
||||||
<parent>
|
<groupId>com.baeldung</groupId>
|
||||||
<groupId>com.baeldung</groupId>
|
<artifactId>parent-java</artifactId>
|
||||||
<artifactId>parent-java</artifactId>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<relativePath>../../parent-java</relativePath>
|
||||||
<relativePath>../parent-java</relativePath>
|
</parent>
|
||||||
</parent>
|
|
||||||
|
<dependencies>
|
||||||
<dependencies>
|
<dependency>
|
||||||
<dependency>
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
<groupId>org.openjdk.jmh</groupId>
|
<artifactId>jmh-core</artifactId>
|
||||||
<artifactId>jmh-core</artifactId>
|
<version>${jmh-core.version}</version>
|
||||||
<version>${jmh-core.version}</version>
|
</dependency>
|
||||||
</dependency>
|
<dependency>
|
||||||
<dependency>
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
<groupId>org.openjdk.jmh</groupId>
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
<artifactId>jmh-generator-annprocess</artifactId>
|
<version>${jmh-generator.version}</version>
|
||||||
<version>${jmh-generator.version}</version>
|
</dependency>
|
||||||
</dependency>
|
<dependency>
|
||||||
<dependency>
|
<groupId>log4j</groupId>
|
||||||
<groupId>junit</groupId>
|
<artifactId>log4j</artifactId>
|
||||||
<artifactId>junit</artifactId>
|
<version>${log4j.version}</version>
|
||||||
<version>${junit.version}</version>
|
</dependency>
|
||||||
<scope>test</scope>
|
<dependency>
|
||||||
<type>jar</type>
|
<groupId>junit</groupId>
|
||||||
</dependency>
|
<artifactId>junit</artifactId>
|
||||||
<dependency>
|
<version>${junit.version}</version>
|
||||||
<groupId>org.assertj</groupId>
|
<scope>test</scope>
|
||||||
<artifactId>assertj-core</artifactId>
|
<type>jar</type>
|
||||||
<version>${assertj.version}</version>
|
</dependency>
|
||||||
<scope>test</scope>
|
<dependency>
|
||||||
</dependency>
|
<groupId>org.assertj</groupId>
|
||||||
</dependencies>
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
<properties>
|
<scope>test</scope>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
</dependency>
|
||||||
<maven.compiler.source>1.9</maven.compiler.source>
|
</dependencies>
|
||||||
<maven.compiler.target>1.9</maven.compiler.target>
|
|
||||||
<assertj.version>3.11.1</assertj.version>
|
<properties>
|
||||||
</properties>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<maven.compiler.source>1.9</maven.compiler.source>
|
||||||
|
<maven.compiler.target>1.9</maven.compiler.target>
|
||||||
|
<assertj.version>3.11.1</assertj.version>
|
||||||
|
</properties>
|
||||||
</project>
|
</project>
|
|
@ -1,39 +1,39 @@
|
||||||
package com.baeldung.reduce.application;
|
package com.baeldung.reduce.application;
|
||||||
|
|
||||||
import com.baeldung.reduce.entities.User;
|
import com.baeldung.reduce.entities.User;
|
||||||
import com.baeldung.reduce.utilities.NumberUtils;
|
import com.baeldung.reduce.utilities.NumberUtils;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class Application {
|
public class Application {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
||||||
System.out.println(result1);
|
System.out.println(result1);
|
||||||
|
|
||||||
int result2 = numbers.stream().reduce(0, Integer::sum);
|
int result2 = numbers.stream().reduce(0, Integer::sum);
|
||||||
System.out.println(result2);
|
System.out.println(result2);
|
||||||
|
|
||||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||||
String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
||||||
System.out.println(result3);
|
System.out.println(result3);
|
||||||
|
|
||||||
String result4 = letters.stream().reduce("", String::concat);
|
String result4 = letters.stream().reduce("", String::concat);
|
||||||
System.out.println(result4);
|
System.out.println(result4);
|
||||||
|
|
||||||
String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
||||||
System.out.println(result5);
|
System.out.println(result5);
|
||||||
|
|
||||||
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
||||||
int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||||
System.out.println(result6);
|
System.out.println(result6);
|
||||||
|
|
||||||
String result7 = letters.parallelStream().reduce("", String::concat);
|
String result7 = letters.parallelStream().reduce("", String::concat);
|
||||||
System.out.println(result7);
|
System.out.println(result7);
|
||||||
|
|
||||||
int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||||
System.out.println(result8);
|
System.out.println(result8);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,52 +1,52 @@
|
||||||
package com.baeldung.reduce.benchmarks;
|
package com.baeldung.reduce.benchmarks;
|
||||||
|
|
||||||
import com.baeldung.reduce.entities.User;
|
import com.baeldung.reduce.entities.User;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import org.openjdk.jmh.annotations.Benchmark;
|
import org.openjdk.jmh.annotations.Benchmark;
|
||||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||||
import org.openjdk.jmh.annotations.Mode;
|
import org.openjdk.jmh.annotations.Mode;
|
||||||
import org.openjdk.jmh.annotations.Scope;
|
import org.openjdk.jmh.annotations.Scope;
|
||||||
import org.openjdk.jmh.annotations.State;
|
import org.openjdk.jmh.annotations.State;
|
||||||
import org.openjdk.jmh.runner.Runner;
|
import org.openjdk.jmh.runner.Runner;
|
||||||
import org.openjdk.jmh.runner.RunnerException;
|
import org.openjdk.jmh.runner.RunnerException;
|
||||||
import org.openjdk.jmh.runner.options.Options;
|
import org.openjdk.jmh.runner.options.Options;
|
||||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||||
|
|
||||||
@State(Scope.Thread)
|
@State(Scope.Thread)
|
||||||
@BenchmarkMode(Mode.AverageTime)
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
public class JMHStreamReduceBenchMark {
|
public class JMHStreamReduceBenchMark {
|
||||||
|
|
||||||
private final List<User> userList = createUsers();
|
private final List<User> userList = createUsers();
|
||||||
|
|
||||||
public static void main(String[] args) throws RunnerException {
|
public static void main(String[] args) throws RunnerException {
|
||||||
|
|
||||||
Options options = new OptionsBuilder()
|
Options options = new OptionsBuilder()
|
||||||
.include(JMHStreamReduceBenchMark.class.getSimpleName()).threads(1)
|
.include(JMHStreamReduceBenchMark.class.getSimpleName()).threads(1)
|
||||||
.forks(1).shouldFailOnError(true).shouldDoGC(true)
|
.forks(1).shouldFailOnError(true).shouldDoGC(true)
|
||||||
.jvmArgs("-server").build();
|
.jvmArgs("-server").build();
|
||||||
new Runner(options).run();
|
new Runner(options).run();
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<User> createUsers() {
|
private List<User> createUsers() {
|
||||||
List<User> users = new ArrayList<>();
|
List<User> users = new ArrayList<>();
|
||||||
for (int i = 0; i <= 1000000; i++) {
|
for (int i = 0; i <= 1000000; i++) {
|
||||||
users.add(new User("John" + i, i));
|
users.add(new User("John" + i, i));
|
||||||
}
|
}
|
||||||
return users;
|
return users;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Benchmark
|
@Benchmark
|
||||||
public Integer executeReduceOnParallelizedStream() {
|
public Integer executeReduceOnParallelizedStream() {
|
||||||
return this.userList
|
return this.userList
|
||||||
.parallelStream()
|
.parallelStream()
|
||||||
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Benchmark
|
@Benchmark
|
||||||
public Integer executeReduceOnSequentialStream() {
|
public Integer executeReduceOnSequentialStream() {
|
||||||
return this.userList
|
return this.userList
|
||||||
.stream()
|
.stream()
|
||||||
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
.reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,25 +1,25 @@
|
||||||
package com.baeldung.reduce.entities;
|
package com.baeldung.reduce.entities;
|
||||||
|
|
||||||
public class User {
|
public class User {
|
||||||
|
|
||||||
private final String name;
|
private final String name;
|
||||||
private final int age;
|
private final int age;
|
||||||
|
|
||||||
public User(String name, int age) {
|
public User(String name, int age) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.age = age;
|
this.age = age;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getAge() {
|
public int getAge() {
|
||||||
return age;
|
return age;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "User{" + "name=" + name + ", age=" + age + '}';
|
return "User{" + "name=" + name + ", age=" + age + '}';
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,52 +1,52 @@
|
||||||
package com.baeldung.reduce.utilities;
|
package com.baeldung.reduce.utilities;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.function.BiFunction;
|
import java.util.function.BiFunction;
|
||||||
import java.util.logging.Level;
|
import java.util.logging.Level;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
public abstract class NumberUtils {
|
public abstract class NumberUtils {
|
||||||
|
|
||||||
private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName());
|
private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName());
|
||||||
|
|
||||||
public static int divideListElements(List<Integer> values, Integer divider) {
|
public static int divideListElements(List<Integer> values, Integer divider) {
|
||||||
return values.stream()
|
return values.stream()
|
||||||
.reduce(0, (a, b) -> {
|
.reduce(0, (a, b) -> {
|
||||||
try {
|
try {
|
||||||
return a / divider + b / divider;
|
return a / divider + b / divider;
|
||||||
} catch (ArithmeticException e) {
|
} catch (ArithmeticException e) {
|
||||||
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
|
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public static int divideListElementsWithExtractedTryCatchBlock(List<Integer> values, int divider) {
|
public static int divideListElementsWithExtractedTryCatchBlock(List<Integer> values, int divider) {
|
||||||
return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider));
|
return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static int divideListElementsWithApplyFunctionMethod(List<Integer> values, int divider) {
|
public static int divideListElementsWithApplyFunctionMethod(List<Integer> values, int divider) {
|
||||||
BiFunction<Integer, Integer, Integer> division = (a, b) -> a / b;
|
BiFunction<Integer, Integer, Integer> division = (a, b) -> a / b;
|
||||||
return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider));
|
return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int divide(int value, int factor) {
|
private static int divide(int value, int factor) {
|
||||||
int result = 0;
|
int result = 0;
|
||||||
try {
|
try {
|
||||||
result = value / factor;
|
result = value / factor;
|
||||||
} catch (ArithmeticException e) {
|
} catch (ArithmeticException e) {
|
||||||
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
|
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int applyFunction(BiFunction<Integer, Integer, Integer> function, int a, int b) {
|
private static int applyFunction(BiFunction<Integer, Integer, Integer> function, int a, int b) {
|
||||||
try {
|
try {
|
||||||
return function.apply(a, b);
|
return function.apply(a, b);
|
||||||
}
|
}
|
||||||
catch(Exception e) {
|
catch(Exception e) {
|
||||||
LOGGER.log(Level.INFO, "Exception thrown!");
|
LOGGER.log(Level.INFO, "Exception thrown!");
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.stream.mycollectors;
|
package com.baeldung.streams;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
|
@ -1,79 +1,80 @@
|
||||||
package com.baeldung.reduce.tests;
|
package com.baeldung.reduce;
|
||||||
|
|
||||||
import com.baeldung.reduce.entities.User;
|
import com.baeldung.reduce.entities.User;
|
||||||
import com.baeldung.reduce.utilities.NumberUtils;
|
import com.baeldung.reduce.utilities.NumberUtils;
|
||||||
import java.util.ArrayList;
|
import org.junit.Test;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
import java.util.Arrays;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import java.util.List;
|
||||||
import org.junit.Test;
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
public class StreamReduceUnitTest {
|
|
||||||
|
public class StreamReduceUnitTest {
|
||||||
@Test
|
|
||||||
public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
|
@Test
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
|
||||||
int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
assertThat(result).isEqualTo(21);
|
int result = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
||||||
}
|
assertThat(result).isEqualTo(21);
|
||||||
|
}
|
||||||
@Test
|
|
||||||
public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
|
@Test
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
|
||||||
int result = numbers.stream().reduce(0, Integer::sum);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
assertThat(result).isEqualTo(21);
|
int result = numbers.stream().reduce(0, Integer::sum);
|
||||||
}
|
assertThat(result).isEqualTo(21);
|
||||||
|
}
|
||||||
@Test
|
|
||||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
|
@Test
|
||||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
|
||||||
String result = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||||
assertThat(result).isEqualTo("abcde");
|
String result = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
||||||
}
|
assertThat(result).isEqualTo("abcde");
|
||||||
|
}
|
||||||
@Test
|
|
||||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
|
@Test
|
||||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
|
||||||
String result = letters.stream().reduce("", String::concat);
|
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||||
assertThat(result).isEqualTo("abcde");
|
String result = letters.stream().reduce("", String::concat);
|
||||||
}
|
assertThat(result).isEqualTo("abcde");
|
||||||
|
}
|
||||||
@Test
|
|
||||||
public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
|
@Test
|
||||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
|
||||||
String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||||
assertThat(result).isEqualTo("ABCDE");
|
String result = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
||||||
}
|
assertThat(result).isEqualTo("ABCDE");
|
||||||
|
}
|
||||||
@Test
|
|
||||||
public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
|
@Test
|
||||||
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
|
||||||
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
||||||
assertThat(result).isEqualTo(65);
|
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||||
}
|
assertThat(result).isEqualTo(65);
|
||||||
|
}
|
||||||
@Test
|
|
||||||
public void givenStringList_whenReduceWithParallelStream_thenCorrect() {
|
@Test
|
||||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
public void givenStringList_whenReduceWithParallelStream_thenCorrect() {
|
||||||
String result = letters.parallelStream().reduce("", String::concat);
|
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||||
assertThat(result).isEqualTo("abcde");
|
String result = letters.parallelStream().reduce("", String::concat);
|
||||||
}
|
assertThat(result).isEqualTo("abcde");
|
||||||
|
}
|
||||||
@Test
|
|
||||||
public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
|
@Test
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
|
||||||
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
}
|
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
|
||||||
|
}
|
||||||
@Test
|
|
||||||
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
|
@Test
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
|
||||||
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
}
|
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
|
||||||
|
}
|
||||||
@Test
|
|
||||||
public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
|
@Test
|
||||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
|
||||||
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
|
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||||
}
|
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
|
||||||
}
|
}
|
||||||
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java_8_features;
|
package com.baeldung.streams;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java8.streams;
|
package com.baeldung.streams;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.java8.streams;
|
package com.baeldung.streams;
|
||||||
|
|
||||||
import com.baeldung.stream.Product;
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
|
@ -1,6 +1,5 @@
|
||||||
package com.baeldung.java8;
|
package com.baeldung.streams;
|
||||||
|
|
||||||
import com.baeldung.java_8_features.Detail;
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
|
@ -1,13 +1,13 @@
|
||||||
package com.baeldung.stream;
|
package com.baeldung.streams;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
import java.io.StringWriter;
|
import java.io.StringWriter;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
public class PeekUnitTest {
|
public class PeekUnitTest {
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.stream;
|
package com.baeldung.streams;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.stream;
|
package com.baeldung.streams;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
|
@ -1,16 +1,13 @@
|
||||||
package com.baeldung.stream;
|
package com.baeldung.streams;
|
||||||
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
|
@ -1,20 +1,12 @@
|
||||||
package com.baeldung.stream;
|
package com.baeldung.streams;
|
||||||
|
|
||||||
import static java.util.stream.Collectors.collectingAndThen;
|
|
||||||
import static java.util.stream.Collectors.toList;
|
|
||||||
import static java.util.stream.Collectors.toSet;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.LinkedList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.stream.IntStream;
|
|
||||||
|
|
||||||
|
import com.google.common.collect.ImmutableList;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import com.baeldung.stream.mycollectors.MyImmutableListCollector;
|
import java.util.*;
|
||||||
import com.google.common.collect.ImmutableList;
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import static java.util.stream.Collectors.*;
|
||||||
|
|
||||||
public class StreamToImmutableUnitTest {
|
public class StreamToImmutableUnitTest {
|
||||||
|
|
|
@ -1,9 +1,4 @@
|
||||||
package com.baeldung.stream;
|
package com.baeldung.streams.removeitem;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.function.Predicate;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
|
@ -11,6 +6,11 @@ import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
public class StreamOperateAndRemoveUnitTest {
|
public class StreamOperateAndRemoveUnitTest {
|
||||||
|
|
||||||
private List<Item> itemList;
|
private List<Item> itemList;
|
|
@ -0,0 +1,11 @@
|
||||||
|
## Core Java streams
|
||||||
|
|
||||||
|
This module contains articles about the Stream API in Java.
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap)
|
||||||
|
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
|
||||||
|
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
|
||||||
|
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
||||||
|
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
|
||||||
|
- More articles: [[<-- prev>]](/../core-java-streams-2)
|
|
@ -0,0 +1,53 @@
|
||||||
|
<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-3</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<name>core-java-streams-3</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-java</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-java</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>${lombok.version}</version>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
<!-- test scoped -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-streams-3</finalName>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<!-- testing -->
|
||||||
|
<assertj.version>3.6.1</assertj.version>
|
||||||
|
<!-- plugins -->
|
||||||
|
<maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.forEach;
|
package com.baeldung.streams.forEach;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.stream;
|
package com.baeldung.streams.primitivestreams;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.stream.IntStream;
|
import java.util.stream.IntStream;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.collectors;
|
package com.baeldung.streams.collectors;
|
||||||
|
|
||||||
import com.google.common.collect.ImmutableList;
|
import com.google.common.collect.ImmutableList;
|
||||||
import com.google.common.collect.ImmutableSet;
|
import com.google.common.collect.ImmutableSet;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.stream.conditional;
|
package com.baeldung.streams.conditional;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
|
@ -1,14 +1,14 @@
|
||||||
package com.baeldung.stream;
|
package com.baeldung.streams.primitivestreams;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import org.junit.Test;
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import java.util.stream.IntStream;
|
import java.util.stream.IntStream;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
import org.junit.Test;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class PrimitiveStreamsUnitTest {
|
public class PrimitiveStreamsUnitTest {
|
||||||
|
|
|
@ -1,9 +1,16 @@
|
||||||
=========
|
## Core Java streams
|
||||||
|
|
||||||
## Core Java 8 Cookbooks and Examples
|
This module contains articles about the Stream API in Java.
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [The Difference Between map() and flatMap()](https://www.baeldung.com/java-difference-map-and-flatmap)
|
- [Java 8 and Infinite Streams](https://www.baeldung.com/java-inifinite-streams)
|
||||||
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
|
- [How to Get the Last Element of a Stream in Java?](https://www.baeldung.com/java-stream-last-element)
|
||||||
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
|
- [“Stream has already been operated upon or closed” Exception in Java](https://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
|
||||||
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
- [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)
|
||||||
|
- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack)
|
||||||
|
- [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)
|
||||||
|
- More articles: [[next -->]](/../core-java-streams-2)
|
|
@ -14,6 +14,34 @@
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<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>
|
||||||
<!-- test scoped -->
|
<!-- test scoped -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.assertj</groupId>
|
<groupId>org.assertj</groupId>
|
||||||
|
@ -21,6 +49,36 @@
|
||||||
<version>${assertj.version}</version>
|
<version>${assertj.version}</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</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>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -31,10 +89,33 @@
|
||||||
<filtering>true</filtering>
|
<filtering>true</filtering>
|
||||||
</resource>
|
</resource>
|
||||||
</resources>
|
</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>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
<!-- util -->
|
||||||
|
<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>
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
<assertj.version>3.6.1</assertj.version>
|
<assertj.version>3.11.1</assertj.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>
|
</properties>
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -1,8 +1,8 @@
|
||||||
package com.baeldung.stream.sum;
|
package com.baeldung.stream.sum;
|
||||||
|
|
||||||
public class ArithmeticUtils {
|
public class ArithmeticUtils {
|
||||||
|
|
||||||
public static int add(int a, int b) {
|
public static int add(int a, int b) {
|
||||||
return a + b;
|
return a + b;
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,31 +1,31 @@
|
||||||
package com.baeldung.stream.sum;
|
package com.baeldung.stream.sum;
|
||||||
|
|
||||||
public class Item {
|
public class Item {
|
||||||
|
|
||||||
private int id;
|
private int id;
|
||||||
private Integer price;
|
private Integer price;
|
||||||
|
|
||||||
public Item(int id, Integer price) {
|
public Item(int id, Integer price) {
|
||||||
super();
|
super();
|
||||||
this.id = id;
|
this.id = id;
|
||||||
this.price = price;
|
this.price = price;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Standard getters and setters
|
// Standard getters and setters
|
||||||
public long getId() {
|
public long getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(int id) {
|
public void setId(int id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Integer getPrice() {
|
public Integer getPrice() {
|
||||||
return price;
|
return price;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setPrice(Integer price) {
|
public void setPrice(Integer price) {
|
||||||
this.price = price;
|
this.price = price;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,59 +1,59 @@
|
||||||
package com.baeldung.stream.sum;
|
package com.baeldung.stream.sum;
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
public class StreamSumCalculator {
|
public class StreamSumCalculator {
|
||||||
|
|
||||||
public static Integer getSumUsingCustomizedAccumulator(List<Integer> integers) {
|
public static Integer getSumUsingCustomizedAccumulator(List<Integer> integers) {
|
||||||
return integers.stream()
|
return integers.stream()
|
||||||
.reduce(0, ArithmeticUtils::add);
|
.reduce(0, ArithmeticUtils::add);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Integer getSumUsingJavaAccumulator(List<Integer> integers) {
|
public static Integer getSumUsingJavaAccumulator(List<Integer> integers) {
|
||||||
return integers.stream()
|
return integers.stream()
|
||||||
.reduce(0, Integer::sum);
|
.reduce(0, Integer::sum);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Integer getSumUsingReduce(List<Integer> integers) {
|
public static Integer getSumUsingReduce(List<Integer> integers) {
|
||||||
return integers.stream()
|
return integers.stream()
|
||||||
.reduce(0, (a, b) -> a + b);
|
.reduce(0, (a, b) -> a + b);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Integer getSumUsingCollect(List<Integer> integers) {
|
public static Integer getSumUsingCollect(List<Integer> integers) {
|
||||||
|
|
||||||
return integers.stream()
|
return integers.stream()
|
||||||
.collect(Collectors.summingInt(Integer::intValue));
|
.collect(Collectors.summingInt(Integer::intValue));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Integer getSumUsingSum(List<Integer> integers) {
|
public static Integer getSumUsingSum(List<Integer> integers) {
|
||||||
|
|
||||||
return integers.stream()
|
return integers.stream()
|
||||||
.mapToInt(Integer::intValue)
|
.mapToInt(Integer::intValue)
|
||||||
.sum();
|
.sum();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Integer getSumOfMapValues(Map<Object, Integer> map) {
|
public static Integer getSumOfMapValues(Map<Object, Integer> map) {
|
||||||
|
|
||||||
return map.values()
|
return map.values()
|
||||||
.stream()
|
.stream()
|
||||||
.mapToInt(Integer::valueOf)
|
.mapToInt(Integer::valueOf)
|
||||||
.sum();
|
.sum();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Integer getSumIntegersFromString(String str) {
|
public static Integer getSumIntegersFromString(String str) {
|
||||||
|
|
||||||
Integer sum = Arrays.stream(str.split(" "))
|
Integer sum = Arrays.stream(str.split(" "))
|
||||||
.filter((s) -> s.matches("\\d+"))
|
.filter((s) -> s.matches("\\d+"))
|
||||||
.mapToInt(Integer::valueOf)
|
.mapToInt(Integer::valueOf)
|
||||||
.sum();
|
.sum();
|
||||||
|
|
||||||
return sum;
|
return sum;
|
||||||
}
|
}
|
||||||
}
|
}
|
|
@ -1,38 +1,38 @@
|
||||||
package com.baeldung.stream.sum;
|
package com.baeldung.stream.sum;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
public class StreamSumCalculatorWithObject {
|
public class StreamSumCalculatorWithObject {
|
||||||
|
|
||||||
public static Integer getSumUsingCustomizedAccumulator(List<Item> items) {
|
public static Integer getSumUsingCustomizedAccumulator(List<Item> items) {
|
||||||
return items.stream()
|
return items.stream()
|
||||||
.map(x -> x.getPrice())
|
.map(x -> x.getPrice())
|
||||||
.reduce(0, ArithmeticUtils::add);
|
.reduce(0, ArithmeticUtils::add);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Integer getSumUsingJavaAccumulator(List<Item> items) {
|
public static Integer getSumUsingJavaAccumulator(List<Item> items) {
|
||||||
return items.stream()
|
return items.stream()
|
||||||
.map(x -> x.getPrice())
|
.map(x -> x.getPrice())
|
||||||
.reduce(0, Integer::sum);
|
.reduce(0, Integer::sum);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Integer getSumUsingReduce(List<Item> items) {
|
public static Integer getSumUsingReduce(List<Item> items) {
|
||||||
return items.stream()
|
return items.stream()
|
||||||
.map(item -> item.getPrice())
|
.map(item -> item.getPrice())
|
||||||
.reduce(0, (a, b) -> a + b);
|
.reduce(0, (a, b) -> a + b);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Integer getSumUsingCollect(List<Item> items) {
|
public static Integer getSumUsingCollect(List<Item> items) {
|
||||||
return items.stream()
|
return items.stream()
|
||||||
.map(x -> x.getPrice())
|
.map(x -> x.getPrice())
|
||||||
.collect(Collectors.summingInt(Integer::intValue));
|
.collect(Collectors.summingInt(Integer::intValue));
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Integer getSumUsingSum(List<Item> items) {
|
public static Integer getSumUsingSum(List<Item> items) {
|
||||||
return items.stream()
|
return items.stream()
|
||||||
.mapToInt(x -> x.getPrice())
|
.mapToInt(x -> x.getPrice())
|
||||||
.sum();
|
.sum();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.java.conversion;
|
package com.baeldung.conversion;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue