Merge branch 'master' into BAEL-3335

This commit is contained in:
sumit-bhawsar 2019-11-07 17:28:46 +00:00 committed by GitHub
commit 397579079a
1062 changed files with 13751 additions and 8423 deletions

8
.gitignore vendored
View File

@ -84,4 +84,10 @@ software-security/sql-injection-samples/derby.log
spring-soap/src/main/java/com/baeldung/springsoap/gen/
/report-*.json
transaction.log
*-shell.log
*-shell.log
apache-cxf/cxf-aegis/baeldung.xml
apache-fop/src/test/resources/input.xml
apache-fop/src/test/resources/output_herold.pdf
apache-fop/src/test/resources/output_html2fo.pdf
apache-fop/src/test/resources/output_jtidy.pdf

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

After

Width:  |  Height:  |  Size: 10 KiB

View File

@ -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)
- [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)
- [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)

View File

@ -1,7 +1,6 @@
## Algorithms - Miscellaneous
This module contains articles about algorithms. Some classes of algorithms, e.g., [sorting](/../algorithms-sorting) and
[genetic algorithms](/../algorithms-genetic), have their own dedicated modules.
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.
### 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 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)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-3) [[next -->]](/../algorithms-miscellaneous-5)
- More articles: [[<-- prev]](/algorithms-miscellaneous-3) [[next -->]](/algorithms-miscellaneous-5)

View File

@ -0,0 +1,37 @@
package com.baeldung.algorithms.smallestinteger;
import java.util.Arrays;
public class SmallestMissingPositiveInteger {
public static int searchInSortedArray(int[] input) {
for (int i = 0; i < input.length; i++) {
if (i != input[i]) {
return i;
}
}
return input.length;
}
public static int searchInUnsortedArraySortingFirst(int[] input) {
Arrays.sort(input);
return searchInSortedArray(input);
}
public static int searchInUnsortedArrayBooleanArray(int[] input) {
boolean[] flags = new boolean[input.length];
for (int number : input) {
if (number < flags.length) {
flags[number] = true;
}
}
for (int i = 0; i < flags.length; i++) {
if (!flags[i]) {
return i;
}
}
return flags.length;
}
}

View File

@ -0,0 +1,88 @@
package com.baeldung.algorithms.smallestinteger;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class SmallestMissingPositiveIntegerUnitTest {
@Test
void givenArrayWithThreeMissing_whenSearchInSortedArray_thenThree() {
int[] input = new int[] {0, 1, 2, 4, 5};
int result = SmallestMissingPositiveInteger.searchInSortedArray(input);
assertThat(result).isEqualTo(3);
}
@Test
void givenArrayWithOneAndThreeMissing_whenSearchInSortedArray_thenOne() {
int[] input = new int[] {0, 2, 4, 5};
int result = SmallestMissingPositiveInteger.searchInSortedArray(input);
assertThat(result).isEqualTo(1);
}
@Test
void givenArrayWithoutMissingInteger_whenSearchInSortedArray_thenArrayLength() {
int[] input = new int[] {0, 1, 2, 3, 4, 5};
int result = SmallestMissingPositiveInteger.searchInSortedArray(input);
assertThat(result).isEqualTo(input.length);
}
@Test
void givenArrayWithThreeMissing_whenSearchInUnsortedArraySortingFirst_thenThree() {
int[] input = new int[] {1, 4, 0, 5, 2};
int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input);
assertThat(result).isEqualTo(3);
}
@Test
void givenArrayWithOneAndThreeMissing_whenSearchInUnsortedArraySortingFirst_thenOne() {
int[] input = new int[] {4, 2, 0, 5};
int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input);
assertThat(result).isEqualTo(1);
}
@Test
void givenArrayWithoutMissingInteger_whenSearchInUnsortedArraySortingFirst_thenArrayLength() {
int[] input = new int[] {4, 5, 1, 3, 0, 2};
int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input);
assertThat(result).isEqualTo(input.length);
}
@Test
void givenArrayWithThreeMissing_whenSearchInUnsortedArrayBooleanArray_thenThree() {
int[] input = new int[] {1, 4, 0, 5, 2};
int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);
assertThat(result).isEqualTo(3);
}
@Test
void givenArrayWithOneAndThreeMissing_whenSearchInUnsortedArrayBooleanArray_thenOne() {
int[] input = new int[] {4, 2, 0, 5};
int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);
assertThat(result).isEqualTo(1);
}
@Test
void givenArrayWithoutMissingInteger_whenSearchInUnsortedArrayBooleanArray_thenArrayLength() {
int[] input = new int[] {4, 5, 1, 3, 0, 2};
int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);
assertThat(result).isEqualTo(input.length);
}
}

View File

@ -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)
- [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)
- [Knapsack Problem Implementation in Java](https://www.baeldung.com/java-knapsack)
- More articles: [[<-- prev]](/../algorithms-miscellaneous-4)

View File

@ -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;
}
}
}

View File

@ -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()
);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.algorithms.binarygap;
public class BinaryGap {
static int calculateBinaryGap(int n) {
return calculateBinaryGap(n >>> Integer.numberOfTrailingZeros(n), 0, 0);
}
static int calculateBinaryGap(int n, int current, int maximum) {
if (n == 0) {
return maximum;
} else if ((n & 1) == 0) {
return calculateBinaryGap(n >>> 1, current + 1, maximum);
} else {
return calculateBinaryGap(n >>> 1, 0, Math.max(maximum, current));
}
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.algorithms.knapsack;
public class Knapsack {
public int knapsackRec(int[] w, int[] v, int n, int W) {
if (n <= 0) {
return 0;
} else if (w[n - 1] > W) {
return knapsackRec(w, v, n - 1, W);
} else {
return Math.max(knapsackRec(w, v, n - 1, W), v[n - 1] + knapsackRec(w, v, n - 1, W - w[n - 1]));
}
}
public int knapsackDP(int[] w, int[] v, int n, int W) {
if (n <= 0 || W <= 0) {
return 0;
}
int[][] m = new int[n + 1][W + 1];
for (int j = 0; j <= W; j++) {
m[0][j] = 0;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= W; j++) {
if (w[i - 1] > j) {
m[i][j] = m[i - 1][j];
} else {
m[i][j] = Math.max(m[i - 1][j], m[i - 1][j - w[i - 1]] + v[i - 1]);
}
}
}
return m[n][W];
}
}

View File

@ -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";
}
}

View File

@ -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);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.algorithms.binarygap;
import static com.baeldung.algorithms.binarygap.BinaryGap.calculateBinaryGap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class BinaryGapUnitTest {
@Test public void givenNoOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(63);
assertEquals(0, result);
}
@Test public void givenTrailingZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(40);
assertEquals(1, result);
}
@Test public void givenSingleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(9);
assertEquals(2, result);
}
@Test public void givenMultipleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() {
int result = calculateBinaryGap(145);
assertEquals(3, result);
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.algorithms.knapsack;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class KnapsackUnitTest {
@Test
public void givenWeightsandValues_whenCalculateMax_thenOutputCorrectResult() {
final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 };
final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 };
final int n = 10;
final int W = 67;
final Knapsack knapsack = new Knapsack();
assertEquals(1270, knapsack.knapsackRec(w, v, n, W));
assertEquals(1270, knapsack.knapsackDP(w, v, n, W));
}
@Test
public void givenZeroItems_whenCalculateMax_thenOutputZero() {
final int[] w = new int[] {};
final int[] v = new int[] {};
final int n = 0;
final int W = 67;
final Knapsack knapsack = new Knapsack();
assertEquals(0, knapsack.knapsackRec(w, v, n, W));
assertEquals(0, knapsack.knapsackDP(w, v, n, W));
}
@Test
public void givenZeroWeightLimit_whenCalculateMax_thenOutputZero() {
final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 };
final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 };
final int n = 10;
final int W = 0;
final Knapsack knapsack = new Knapsack();
assertEquals(0, knapsack.knapsackRec(w, v, n, W));
assertEquals(0, knapsack.knapsackDP(w, v, n, W));
}
}

View File

@ -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)
- [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)
- [Bucket Sort in Java](https://www.baeldung.com/java-bucket-sort)

File diff suppressed because it is too large Load Diff

View File

@ -12,10 +12,16 @@
</parent>
<dependencies>
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value-annotations</artifactId>
<version>${auto-value.version}</version>
</dependency>
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value</artifactId>
<version>${auto-value.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.auto.factory</groupId>
@ -43,9 +49,9 @@
</dependencies>
<properties>
<auto-value.version>1.3</auto-value.version>
<auto-factory.version>1.0-beta5</auto-factory.version>
<auto-service.version>1.0-rc5</auto-service.version>
<auto-value.version>1.6.6</auto-value.version>
<auto-factory.version>1.0-beta6</auto-factory.version>
<auto-service.version>1.0-rc6</auto-service.version>
<guice.version>4.2.0</guice.version>
</properties>

View File

@ -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();
}
}
}

View File

@ -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());
}
}

View File

@ -12,4 +12,5 @@ This module contains articles about core Groovy concepts
- [Concatenate Strings with Groovy](https://www.baeldung.com/groovy-concatenate-strings)
- [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)
- [Categories in Groovy](https://www.baeldung.com/groovy-categories)
- [[<-- Prev]](/core-groovy)

View File

@ -5,4 +5,6 @@ This module contains articles about Groovy core collections
## Relevant articles:
- [Maps in Groovy](https://www.baeldung.com/groovy-maps)
- [Finding Elements in Collections in Groovy](https://www.baeldung.com/groovy-collections-find-elements)
- [Lists in Groovy](https://www.baeldung.com/groovy-lists)
- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating)

View File

@ -1,11 +1,11 @@
package com.baeldung.lists
package com.baeldung.find
import com.baeldung.Person
import com.baeldung.find.Person
import org.junit.Test
import static org.junit.Assert.*
class ListUnitTest {
class ListFindUnitTest {
private final personList = [
new Person("Regina", "Fitzpatrick", 25),

View File

@ -1,11 +1,11 @@
package com.baeldung.map
package com.baeldung.find
import com.baeldung.Person
import com.baeldung.find.Person
import org.junit.Test
import static org.junit.Assert.*
class MapUnitTest {
class MapFindUnitTest {
private final personMap = [
Regina : new Person("Regina", "Fitzpatrick", 25),
@ -13,84 +13,6 @@ class MapUnitTest {
Lucian : new Person("Lucian", "Walter", 30)
]
@Test
void whenUsingEach_thenMapIsIterated() {
def map = [
'FF0000' : 'Red',
'00FF00' : 'Lime',
'0000FF' : 'Blue',
'FFFF00' : 'Yellow'
]
map.each { println "Hex Code: $it.key = Color Name: $it.value" }
}
@Test
void whenUsingEachWithEntry_thenMapIsIterated() {
def map = [
'E6E6FA' : 'Lavender',
'D8BFD8' : 'Thistle',
'DDA0DD' : 'Plum',
]
map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" }
}
@Test
void whenUsingEachWithKeyAndValue_thenMapIsIterated() {
def map = [
'000000' : 'Black',
'FFFFFF' : 'White',
'808080' : 'Gray'
]
map.each { key, val ->
println "Hex Code: $key = Color Name $val"
}
}
@Test
void whenUsingEachWithIndexAndEntry_thenMapIsIterated() {
def map = [
'800080' : 'Purple',
'4B0082' : 'Indigo',
'6A5ACD' : 'Slate Blue'
]
map.eachWithIndex { entry, index ->
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
println "$indent Hex Code: $entry.key = Color Name: $entry.value"
}
}
@Test
void whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated() {
def map = [
'FFA07A' : 'Light Salmon',
'FF7F50' : 'Coral',
'FF6347' : 'Tomato',
'FF4500' : 'Orange Red'
]
map.eachWithIndex { key, val, index ->
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
println "$indent Hex Code: $key = Color Name: $val"
}
}
@Test
void whenUsingForLoop_thenMapIsIterated() {
def map = [
'2E8B57' : 'Seagreen',
'228B22' : 'Forest Green',
'008000' : 'Green'
]
for (entry in map) {
println "Hex Code: $entry.key = Color Name: $entry.value"
}
}
@Test
void whenMapContainsKeyElement_thenCheckReturnsTrue() {
def map = [a: 'd', b: 'e', c: 'f']

View File

@ -1,4 +1,4 @@
package com.baeldung
package com.baeldung.find
class Person {
private String firstname

View File

@ -1,10 +1,10 @@
package com.baeldung.set
package com.baeldung.find
import org.junit.Test
import static org.junit.Assert.assertTrue
class SetUnitTest {
class SetFindUnitTest {
@Test
void whenSetContainsElement_thenCheckReturnsTrue() {

View File

@ -0,0 +1,87 @@
package com.baeldung.iteratemap
import com.baeldung.find.Person
import org.junit.Test
import static org.junit.Assert.*
class IterateMapUnitTest {
@Test
void whenUsingEach_thenMapIsIterated() {
def map = [
'FF0000' : 'Red',
'00FF00' : 'Lime',
'0000FF' : 'Blue',
'FFFF00' : 'Yellow'
]
map.each { println "Hex Code: $it.key = Color Name: $it.value" }
}
@Test
void whenUsingEachWithEntry_thenMapIsIterated() {
def map = [
'E6E6FA' : 'Lavender',
'D8BFD8' : 'Thistle',
'DDA0DD' : 'Plum',
]
map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" }
}
@Test
void whenUsingEachWithKeyAndValue_thenMapIsIterated() {
def map = [
'000000' : 'Black',
'FFFFFF' : 'White',
'808080' : 'Gray'
]
map.each { key, val ->
println "Hex Code: $key = Color Name $val"
}
}
@Test
void whenUsingEachWithIndexAndEntry_thenMapIsIterated() {
def map = [
'800080' : 'Purple',
'4B0082' : 'Indigo',
'6A5ACD' : 'Slate Blue'
]
map.eachWithIndex { entry, index ->
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
println "$indent Hex Code: $entry.key = Color Name: $entry.value"
}
}
@Test
void whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated() {
def map = [
'FFA07A' : 'Light Salmon',
'FF7F50' : 'Coral',
'FF6347' : 'Tomato',
'FF4500' : 'Orange Red'
]
map.eachWithIndex { key, val, index ->
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
println "$indent Hex Code: $key = Color Name: $val"
}
}
@Test
void whenUsingForLoop_thenMapIsIterated() {
def map = [
'2E8B57' : 'Seagreen',
'228B22' : 'Forest Green',
'008000' : 'Green'
]
for (entry in map) {
println "Hex Code: $entry.key = Color Name: $entry.value"
}
}
}

View File

@ -1,9 +1,9 @@
package com.baeldung.groovy.lists
package com.baeldung.lists
import static groovy.test.GroovyAssert.*
import org.junit.Test
class ListTest{
class ListUnitTest {
@Test
void testCreateList() {

View File

@ -1,4 +1,4 @@
package com.baeldung.map;
package com.baeldung.maps;
import static groovy.test.GroovyAssert.*
import org.junit.Test

View File

@ -8,11 +8,8 @@ This module contains articles about core Groovy concepts
- [Working with JSON in Groovy](https://www.baeldung.com/groovy-json)
- [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read)
- [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings)
- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating)
- [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits)
- [Closures in Groovy](https://www.baeldung.com/groovy-closures)
- [Finding Elements in Collections in Groovy](https://www.baeldung.com/groovy-collections-find-elements)
- [Lists in Groovy](https://www.baeldung.com/groovy-lists)
- [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date)
- [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io)
- [[More -->]](/core-groovy-2)

View File

@ -1,148 +0,0 @@
package com.baeldung.groovy.map;
import static groovy.test.GroovyAssert.*
import org.junit.Test
class MapTest{
@Test
void createMap() {
def emptyMap = [:]
assertNotNull(emptyMap)
assertTrue(emptyMap instanceof java.util.LinkedHashMap)
def map = [name:"Jerry", age: 42, city: "New York"]
assertTrue(map.size() == 3)
}
@Test
void addItemsToMap() {
def map = [name:"Jerry"]
map["age"] = 42
map.city = "New York"
def hobbyLiteral = "hobby"
def hobbyMap = [(hobbyLiteral): "Singing"]
map.putAll(hobbyMap)
assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"])
assertTrue(hobbyMap.hobby == "Singing")
assertTrue(hobbyMap[hobbyLiteral] == "Singing")
map.plus([1:20]) // returns new map
map << [2:30]
}
@Test
void getItemsFromMap() {
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
assertTrue(map["name"] == "Jerry")
assertTrue(map.name == "Jerry")
def propertyAge = "age"
assertTrue(map[propertyAge] == 42)
}
@Test
void removeItemsFromMap() {
def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49]
def minusMap = map.minus([2:42, 4:34]);
assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49])
minusMap.removeAll{it -> it.key instanceof String}
assertTrue( minusMap == [ 1:20, 6:39, 7:49])
minusMap.retainAll{it -> it.value %2 == 0}
assertTrue( minusMap == [1:20])
}
@Test
void iteratingOnMaps(){
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
map.each{ entry -> println "$entry.key: $entry.value" }
map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" }
map.eachWithIndex{ key, value, i -> println "$i $key: $value" }
}
@Test
void filteringAndSearchingMaps(){
def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
assertTrue(map.find{ it.value == "New York"}.key == "city")
assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"])
map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")}
assertTrue(map.every{it -> it.value instanceof String} == false)
assertTrue(map.any{it -> it.value instanceof String} == true)
}
@Test
void collect(){
def map = [1: [name:"Jerry", age: 42, city: "New York"],
2: [name:"Long", age: 25, city: "New York"],
3: [name:"Dustin", age: 29, city: "New York"],
4: [name:"Dustin", age: 34, city: "New York"]]
def names = map.collect{entry -> entry.value.name} // returns only list
assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"])
def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name}
assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set)
def idNames = map.collectEntries{key, value -> [key, value.name]}
assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"])
def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name}
assertTrue(below30Names == ["Long", "Dustin"])
}
@Test
void group(){
def map = [1:20, 2: 40, 3: 11, 4: 93]
def subMap = map.groupBy{it.value % 2}
println subMap
assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]])
def keySubMap = map.subMap([1, 2])
assertTrue(keySubMap == [1:20, 2:40])
}
@Test
void sorting(){
def map = [ab:20, a: 40, cb: 11, ba: 93]
def naturallyOrderedMap = map.sort()
assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap)
def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator)
assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap)
def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value })
assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap)
}
}

View File

@ -5,6 +5,5 @@ This module contains modules about core Java
## Relevant articles:
- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
- [Guide to Java FileChannel](https://www.baeldung.com/java-filechannel)
- [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception)
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)

View File

@ -1,12 +1,12 @@
package com.baeldung.java_8_features.groupingby;
public class Tuple {
import java.util.Objects;
public class Tuple {
private final BlogPostType type;
private final String author;
private BlogPostType type;
private String author;
public Tuple(BlogPostType type, String author) {
super();
this.type = type;
this.author = author;
}
@ -15,20 +15,27 @@ public class Tuple {
return type;
}
public void setType(BlogPostType type) {
this.type = type;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Tuple tuple = (Tuple) o;
return type == tuple.type && author.equals(tuple.author);
}
@Override
public int hashCode() {
return Objects.hash(type, author);
}
@Override
public String toString() {
return "Tuple [type=" + type + ", author=" + author + ", getType()=" + getType() + ", getAuthor()=" + getAuthor() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]";
return "Tuple{" + "type=" + type + ", author='" + author + '\'' + '}';
}
}

View File

@ -1,15 +1,32 @@
package com.baeldung.java_8_features.groupingby;
import com.baeldung.java_8_features.groupingby.BlogPost;
import com.baeldung.java_8_features.groupingby.BlogPostType;
import org.junit.Test;
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.averagingInt;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.groupingByConcurrent;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.summarizingInt;
import static java.util.stream.Collectors.summingInt;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.*;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.*;
import static org.junit.Assert.*;
import org.junit.Test;
public class Java8GroupingByCollectorUnitTest {
@ -180,4 +197,19 @@ public class Java8GroupingByCollectorUnitTest {
assertEquals(15, newsLikeStatistics.getMin());
}
@Test
public void givenAListOfPosts_whenGroupedByComplexMapKeyType_thenGetAMapBetweenTupleAndList() {
Map<Tuple, List<BlogPost>> postsPerTypeAndAuthor = posts.stream()
.collect(groupingBy(post -> new Tuple(post.getType(), post.getAuthor())));
List<BlogPost> result = postsPerTypeAndAuthor.get(new Tuple(BlogPostType.GUIDE, "Author 1"));
assertThat(result.size()).isEqualTo(1);
BlogPost blogPost = result.get(0);
assertThat(blogPost.getTitle()).isEqualTo("Programming guide");
assertThat(blogPost.getType()).isEqualTo(BlogPostType.GUIDE);
assertThat(blogPost.getAuthor()).isEqualTo("Author 1");
}
}

View File

@ -0,0 +1,17 @@
## Core Java 9
This module contains articles about the improvements to core Java features introduced with Java 9.
### Relevant Articles:
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional)
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture)
#### Relevant articles not in this module:
- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api) (see the [core-java-os](/core-java-os) module)

View File

@ -0,0 +1,73 @@
<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</artifactId>
<version>0.2-SNAPSHOT</version>
<name>core-java-9</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-9</finalName>
<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>
</configuration>
</plugin>
</plugins>
</build>
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<properties>
<!-- testing -->
<assertj.version>3.10.0</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>
<awaitility.version>1.7.0</awaitility.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
<guava.version>25.1-jre</guava.version>
</properties>
</project>

View File

@ -0,0 +1,11 @@
## Core Java 9
This module contains articles about Project Jigsaw and the Java Platform Module System (JPMS), introduced with Java 9.
### Relevant Articles:
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)
- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity)
- [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api)

View File

@ -0,0 +1,35 @@
<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-jigsaw</artifactId>
<version>0.2-SNAPSHOT</version>
<name>core-java-9</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<build>
<finalName>core-java-9-jigsaw</finalName>
<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>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,14 @@
## Core Java 9
This module contains articles about core Java features that have been introduced in Java 9.
### Relevant Articles:
- [Java 9 New Features](https://www.baeldung.com/new-java-9)
- [Java 9 Variable Handles Demystified](http://www.baeldung.com/java-variable-handles)
- [Exploring the New HTTP Client in Java 9 and 11](http://www.baeldung.com/java-9-http-client)
- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar)
- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation)
- [Introduction to Java 9 StackWalking API](https://www.baeldung.com/java-9-stackwalking-api)
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)

View File

@ -0,0 +1,60 @@
<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-new-features</artifactId>
<version>0.2-SNAPSHOT</version>
<name>core-java-9</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-9-new-features</finalName>
<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>
</configuration>
</plugin>
</plugins>
</build>
<pluginRepositories>
<pluginRepository>
<id>apache.snapshots</id>
<url>http://repository.apache.org/snapshots/</url>
</pluginRepository>
</pluginRepositories>
<properties>
<!-- testing -->
<assertj.version>3.10.0</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
</properties>
</project>

Some files were not shown because too many files have changed in this diff Show More