Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
a4a00a10f8
|
@ -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
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -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>
|
||||
|
||||
|
|
|
@ -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)
|
||||
- [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)
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -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),
|
|
@ -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']
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung
|
||||
package com.baeldung.find
|
||||
|
||||
class Person {
|
||||
private String firstname
|
|
@ -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() {
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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() {
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.map;
|
||||
package com.baeldung.maps;
|
||||
|
||||
import static groovy.test.GroovyAssert.*
|
||||
import org.junit.Test
|
|
@ -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)
|
|
@ -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)
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -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 + '\'' + '}';
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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.function.BiConsumer;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.breakforeach;
|
||||
package com.baeldung.streams.breakforeach;
|
||||
|
||||
import java.util.Spliterator;
|
||||
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.stream.Stream;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.breakforeach;
|
||||
package com.baeldung.streams.breakforeach;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.breakforeach;
|
||||
package com.baeldung.streams.breakforeach;
|
||||
|
||||
import org.junit.Test;
|
||||
|
|
@ -8,4 +8,5 @@
|
|||
- [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs)
|
||||
- [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated)
|
||||
- [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)
|
||||
- [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)
|
||||
- [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)
|
||||
|
|
|
@ -12,4 +12,4 @@
|
|||
- [Sorting in Java](https://www.baeldung.com/java-sorting)
|
||||
- [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)
|
||||
|
||||
- [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)
|
||||
- [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)
|
||||
- [[<-- 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,42 @@
|
|||
package com.baeldung.list;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Demo different approaches to get count of duplicated elements in an
|
||||
* arrayList
|
||||
*/
|
||||
public class DuplicatesCounter {
|
||||
|
||||
public static <T> Map<T, Long> countByClassicalLoop(List<T> inputList) {
|
||||
Map<T, Long> resultMap = new HashMap<>();
|
||||
for (T element : inputList) {
|
||||
if (resultMap.containsKey(element)) {
|
||||
resultMap.put(element, resultMap.get(element) + 1L);
|
||||
} else {
|
||||
resultMap.put(element, 1L);
|
||||
}
|
||||
}
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
public static <T> Map<T, Long> countByClassicalLoopWithMapCompute(List<T> inputList) {
|
||||
Map<T, Long> resultMap = new HashMap<>();
|
||||
for (T element : inputList) {
|
||||
resultMap.compute(element, (k, v) -> v == null ? 1 : v + 1);
|
||||
}
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
public static <T> Map<T, Long> countByStreamToMap(List<T> inputList) {
|
||||
return inputList.stream().collect(Collectors.toMap(Function.identity(), v -> 1L, Long::sum));
|
||||
}
|
||||
|
||||
public static <T> Map<T, Long> countByStreamGroupBy(List<T> inputList) {
|
||||
return inputList.stream().collect(Collectors.groupingBy(k -> k, Collectors.counting()));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,55 @@
|
|||
package com.baeldung.list;
|
||||
|
||||
import org.assertj.core.util.Lists;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.data.MapEntry.entry;
|
||||
|
||||
class DuplicatesCounterUnitTest {
|
||||
|
||||
|
||||
private static List<String> INPUT_LIST = Lists.list(
|
||||
"expect1",
|
||||
"expect2", "expect2",
|
||||
"expect3", "expect3", "expect3",
|
||||
"expect4", "expect4", "expect4", "expect4");
|
||||
|
||||
@Test
|
||||
void givenInput_whenCountByClassicalLoop_thenGetResultMap() {
|
||||
Map<String, Long> result = DuplicatesCounter.countByClassicalLoop(INPUT_LIST);
|
||||
verifyResult(result);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void givenInput_whenCountByClassicalLoopWithMapCompute_thenGetResultMap() {
|
||||
Map<String, Long> result = DuplicatesCounter.countByClassicalLoopWithMapCompute(INPUT_LIST);
|
||||
verifyResult(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInput_whenCountByStreamToMap_thenGetResultMap() {
|
||||
Map<String, Long> result = DuplicatesCounter.countByStreamToMap(INPUT_LIST);
|
||||
verifyResult(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenInput_whenCountByStreamGroupBy_thenGetResultMap() {
|
||||
Map<String, Long> result = DuplicatesCounter.countByStreamGroupBy(INPUT_LIST);
|
||||
verifyResult(result);
|
||||
}
|
||||
|
||||
private void verifyResult(Map<String, Long> resultMap) {
|
||||
assertThat(resultMap)
|
||||
.isNotEmpty().hasSize(4)
|
||||
.containsExactly(
|
||||
entry("expect1", 1L),
|
||||
entry("expect2", 2L),
|
||||
entry("expect3", 3L),
|
||||
entry("expect4", 4L));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
## Java Date/time computations Cookbooks and Examples
|
||||
|
||||
This module contains articles about date and time computations in Java.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Difference Between Two Dates in Java](http://www.baeldung.com/java-date-difference)
|
||||
- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time)
|
||||
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
|
||||
- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day)
|
||||
- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar)
|
||||
- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
|
||||
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
|
||||
- [Increment Date in Java](http://www.baeldung.com/java-increment-date)
|
||||
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
|
||||
- [Introduction to Joda-Time](http://www.baeldung.com/joda-time)
|
|
@ -0,0 +1,71 @@
|
|||
<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-datetime-computations</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-datetime-computations</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>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.darwinsys</groupId>
|
||||
<artifactId>hirondelle-date4j</artifactId>
|
||||
<version>RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-datetime-computations</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</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>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
</properties>
|
||||
</project>
|
|
@ -1,28 +1,28 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class DateExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(Date date) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.YEAR);
|
||||
}
|
||||
|
||||
int getMonth(Date date) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.MONTH);
|
||||
}
|
||||
|
||||
int getDay(Date date) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.DAY_OF_MONTH);
|
||||
}
|
||||
}
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class DateExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(Date date) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.YEAR);
|
||||
}
|
||||
|
||||
int getMonth(Date date) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.MONTH);
|
||||
}
|
||||
|
||||
int getDay(Date date) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.DAY_OF_MONTH);
|
||||
}
|
||||
}
|
|
@ -1,18 +1,18 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class LocalDateExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(LocalDate localDate) {
|
||||
return localDate.getYear();
|
||||
}
|
||||
|
||||
int getMonth(LocalDate localDate) {
|
||||
return localDate.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(LocalDate localDate) {
|
||||
return localDate.getDayOfMonth();
|
||||
}
|
||||
}
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class LocalDateExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(LocalDate localDate) {
|
||||
return localDate.getYear();
|
||||
}
|
||||
|
||||
int getMonth(LocalDate localDate) {
|
||||
return localDate.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(LocalDate localDate) {
|
||||
return localDate.getDayOfMonth();
|
||||
}
|
||||
}
|
|
@ -1,18 +1,18 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class LocalDateTimeExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(LocalDateTime localDateTime) {
|
||||
return localDateTime.getYear();
|
||||
}
|
||||
|
||||
int getMonth(LocalDateTime localDateTime) {
|
||||
return localDateTime.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(LocalDateTime localDateTime) {
|
||||
return localDateTime.getDayOfMonth();
|
||||
}
|
||||
}
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class LocalDateTimeExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(LocalDateTime localDateTime) {
|
||||
return localDateTime.getYear();
|
||||
}
|
||||
|
||||
int getMonth(LocalDateTime localDateTime) {
|
||||
return localDateTime.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(LocalDateTime localDateTime) {
|
||||
return localDateTime.getDayOfMonth();
|
||||
}
|
||||
}
|
|
@ -1,18 +1,18 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
public class OffsetDateTimeExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(OffsetDateTime offsetDateTime) {
|
||||
return offsetDateTime.getYear();
|
||||
}
|
||||
|
||||
int getMonth(OffsetDateTime offsetDateTime) {
|
||||
return offsetDateTime.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(OffsetDateTime offsetDateTime) {
|
||||
return offsetDateTime.getDayOfMonth();
|
||||
}
|
||||
}
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
public class OffsetDateTimeExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(OffsetDateTime offsetDateTime) {
|
||||
return offsetDateTime.getYear();
|
||||
}
|
||||
|
||||
int getMonth(OffsetDateTime offsetDateTime) {
|
||||
return offsetDateTime.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(OffsetDateTime offsetDateTime) {
|
||||
return offsetDateTime.getDayOfMonth();
|
||||
}
|
||||
}
|
|
@ -1,18 +1,18 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
public class ZonedDateTimeExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(ZonedDateTime zonedDateTime) {
|
||||
return zonedDateTime.getYear();
|
||||
}
|
||||
|
||||
int getMonth(ZonedDateTime zonedDateTime) {
|
||||
return zonedDateTime.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(ZonedDateTime zonedDateTime) {
|
||||
return zonedDateTime.getDayOfMonth();
|
||||
}
|
||||
}
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
public class ZonedDateTimeExtractYearMonthDayIntegerValues {
|
||||
|
||||
int getYear(ZonedDateTime zonedDateTime) {
|
||||
return zonedDateTime.getYear();
|
||||
}
|
||||
|
||||
int getMonth(ZonedDateTime zonedDateTime) {
|
||||
return zonedDateTime.getMonthValue();
|
||||
}
|
||||
|
||||
int getDay(ZonedDateTime zonedDateTime) {
|
||||
return zonedDateTime.getDayOfMonth();
|
||||
}
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
package com.baeldung.date;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
@ -16,7 +16,7 @@ import java.util.Locale;
|
|||
import java.util.TimeZone;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateDiffUnitTest {
|
||||
|
||||
|
@ -31,14 +31,14 @@ public class DateDiffUnitTest {
|
|||
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() {
|
||||
LocalDate now = LocalDate.now();
|
||||
LocalDate sixDaysBehind = now.minusDays(6);
|
||||
|
||||
Period period = Period.between(now, sixDaysBehind);
|
||||
int diff = period.getDays();
|
||||
int diff = Math.abs(period.getDays());
|
||||
|
||||
assertEquals(diff, 6);
|
||||
}
|
||||
|
@ -68,7 +68,8 @@ public class DateDiffUnitTest {
|
|||
public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() {
|
||||
LocalDateTime ldt = LocalDateTime.now();
|
||||
ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal"));
|
||||
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore")).minusDays(6);
|
||||
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore"))
|
||||
.minusDays(6);
|
||||
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
|
||||
assertEquals(diff, 6);
|
||||
}
|
|
@ -1,45 +1,45 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
DateExtractYearMonthDayIntegerValues extractYearMonthDateIntegerValues = new DateExtractYearMonthDayIntegerValues();
|
||||
|
||||
Date date;
|
||||
|
||||
@Before
|
||||
public void setup() throws ParseException
|
||||
{
|
||||
date=new SimpleDateFormat("dd-MM-yyyy").parse("01-03-2018");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=extractYearMonthDateIntegerValues.getYear(date);
|
||||
assertThat(actualYear,is(2018));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=extractYearMonthDateIntegerValues.getMonth(date);
|
||||
assertThat(actualMonth,is(02));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=extractYearMonthDateIntegerValues.getDay(date);
|
||||
assertThat(actualDayOfMonth,is(01));
|
||||
}
|
||||
}
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class DateExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
DateExtractYearMonthDayIntegerValues extractYearMonthDateIntegerValues = new DateExtractYearMonthDayIntegerValues();
|
||||
|
||||
Date date;
|
||||
|
||||
@Before
|
||||
public void setup() throws ParseException
|
||||
{
|
||||
date=new SimpleDateFormat("dd-MM-yyyy").parse("01-03-2018");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=extractYearMonthDateIntegerValues.getYear(date);
|
||||
assertThat(actualYear,is(2018));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=extractYearMonthDateIntegerValues.getMonth(date);
|
||||
assertThat(actualMonth,is(02));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=extractYearMonthDateIntegerValues.getDay(date);
|
||||
assertThat(actualDayOfMonth,is(01));
|
||||
}
|
||||
}
|
|
@ -1,36 +1,36 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LocalDateExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
LocalDateExtractYearMonthDayIntegerValues localDateExtractYearMonthDayIntegerValues=new LocalDateExtractYearMonthDayIntegerValues();
|
||||
|
||||
LocalDate localDate=LocalDate.parse("2007-12-03");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=localDateExtractYearMonthDayIntegerValues.getYear(localDate);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=localDateExtractYearMonthDayIntegerValues.getMonth(localDate);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=localDateExtractYearMonthDayIntegerValues.getDay(localDate);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LocalDateExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
LocalDateExtractYearMonthDayIntegerValues localDateExtractYearMonthDayIntegerValues=new LocalDateExtractYearMonthDayIntegerValues();
|
||||
|
||||
LocalDate localDate=LocalDate.parse("2007-12-03");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=localDateExtractYearMonthDayIntegerValues.getYear(localDate);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=localDateExtractYearMonthDayIntegerValues.getMonth(localDate);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=localDateExtractYearMonthDayIntegerValues.getDay(localDate);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
|
@ -1,36 +1,36 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
LocalDateTimeExtractYearMonthDayIntegerValues localDateTimeExtractYearMonthDayIntegerValues = new LocalDateTimeExtractYearMonthDayIntegerValues();
|
||||
|
||||
LocalDateTime localDateTime=LocalDateTime.parse("2007-12-03T10:15:30");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=localDateTimeExtractYearMonthDayIntegerValues.getYear(localDateTime);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=localDateTimeExtractYearMonthDayIntegerValues.getMonth(localDateTime);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=localDateTimeExtractYearMonthDayIntegerValues.getDay(localDateTime);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class LocalDateTimeExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
LocalDateTimeExtractYearMonthDayIntegerValues localDateTimeExtractYearMonthDayIntegerValues = new LocalDateTimeExtractYearMonthDayIntegerValues();
|
||||
|
||||
LocalDateTime localDateTime=LocalDateTime.parse("2007-12-03T10:15:30");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=localDateTimeExtractYearMonthDayIntegerValues.getYear(localDateTime);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=localDateTimeExtractYearMonthDayIntegerValues.getMonth(localDateTime);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=localDateTimeExtractYearMonthDayIntegerValues.getDay(localDateTime);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
|
@ -1,36 +1,36 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
OffsetDateTimeExtractYearMonthDayIntegerValues offsetDateTimeExtractYearMonthDayIntegerValues = new OffsetDateTimeExtractYearMonthDayIntegerValues();
|
||||
|
||||
OffsetDateTime offsetDateTime=OffsetDateTime.parse("2007-12-03T10:15:30+01:00");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=offsetDateTimeExtractYearMonthDayIntegerValues.getYear(offsetDateTime);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getMonth(offsetDateTime);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getDay(offsetDateTime);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class OffsetDateTimeExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
OffsetDateTimeExtractYearMonthDayIntegerValues offsetDateTimeExtractYearMonthDayIntegerValues = new OffsetDateTimeExtractYearMonthDayIntegerValues();
|
||||
|
||||
OffsetDateTime offsetDateTime=OffsetDateTime.parse("2007-12-03T10:15:30+01:00");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=offsetDateTimeExtractYearMonthDayIntegerValues.getYear(offsetDateTime);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getMonth(offsetDateTime);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=offsetDateTimeExtractYearMonthDayIntegerValues.getDay(offsetDateTime);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
|
@ -1,36 +1,36 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
ZonedDateTimeExtractYearMonthDayIntegerValues zonedDateTimeExtractYearMonthDayIntegerValues = new ZonedDateTimeExtractYearMonthDayIntegerValues();
|
||||
|
||||
ZonedDateTime zonedDateTime=ZonedDateTime.parse("2007-12-03T10:15:30+01:00");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=zonedDateTimeExtractYearMonthDayIntegerValues.getYear(zonedDateTime);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getMonth(zonedDateTime);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getDay(zonedDateTime);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ZonedDateTimeExtractYearMonthDayIntegerValuesUnitTest {
|
||||
|
||||
ZonedDateTimeExtractYearMonthDayIntegerValues zonedDateTimeExtractYearMonthDayIntegerValues = new ZonedDateTimeExtractYearMonthDayIntegerValues();
|
||||
|
||||
ZonedDateTime zonedDateTime=ZonedDateTime.parse("2007-12-03T10:15:30+01:00");
|
||||
|
||||
@Test
|
||||
public void whenGetYear_thenCorrectYear()
|
||||
{
|
||||
int actualYear=zonedDateTimeExtractYearMonthDayIntegerValues.getYear(zonedDateTime);
|
||||
assertThat(actualYear,is(2007));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetMonth_thenCorrectMonth()
|
||||
{
|
||||
int actualMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getMonth(zonedDateTime);
|
||||
assertThat(actualMonth,is(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetDay_thenCorrectDay()
|
||||
{
|
||||
int actualDayOfMonth=zonedDateTimeExtractYearMonthDayIntegerValues.getDay(zonedDateTime);
|
||||
assertThat(actualDayOfMonth,is(03));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
## Java 8+ Date and Time API
|
||||
|
||||
This module contains articles about the Date and Time API introduced with Java 8.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
|
||||
- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api)
|
||||
- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8)
|
||||
- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster)
|
||||
- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset)
|
||||
- [Differences Between ZonedDateTime and OffsetDateTime](https://www.baeldung.com/java-zoneddatetime-offsetdatetime)
|
||||
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
|
||||
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
|
||||
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
|
||||
- [Comparing Dates in Java](https://www.baeldung.com/java-comparing-dates)
|
|
@ -1,17 +1,16 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>java-dates</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>java-dates</name>
|
||||
<artifactId>core-java-datetime-java8</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-datetime-java8</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -21,11 +20,10 @@
|
|||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
|
@ -33,20 +31,15 @@
|
|||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.darwinsys</groupId>
|
||||
<artifactId>hirondelle-date4j</artifactId>
|
||||
<version>RELEASE</version>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>java-dates</finalName>
|
||||
<finalName>core-java-datetime-java8</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
|
@ -68,10 +61,10 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
</properties>
|
||||
</project>
|
|
@ -36,10 +36,15 @@ class UseLocalDate {
|
|||
}
|
||||
|
||||
LocalDate getFirstDayOfMonth() {
|
||||
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
|
||||
LocalDate firstDayOfMonth = LocalDate.now()
|
||||
.with(TemporalAdjusters.firstDayOfMonth());
|
||||
return firstDayOfMonth;
|
||||
}
|
||||
|
||||
boolean isLeapYear(LocalDate localDate) {
|
||||
return localDate.isLeapYear();
|
||||
}
|
||||
|
||||
LocalDateTime getStartOfDay(LocalDate localDate) {
|
||||
LocalDateTime startofDay = localDate.atStartOfDay();
|
||||
return startofDay;
|
|
@ -2,6 +2,7 @@ package com.baeldung.datetime;
|
|||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.temporal.ChronoField;
|
||||
|
||||
public class UseLocalDateTime {
|
||||
|
@ -21,4 +22,7 @@ public class UseLocalDateTime {
|
|||
return endOfDate;
|
||||
}
|
||||
|
||||
LocalDateTime ofEpochSecond(int epochSecond, ZoneOffset zoneOffset) {
|
||||
return LocalDateTime.ofEpochSecond(epochSecond, 0, zoneOffset);
|
||||
}
|
||||
}
|
|
@ -9,6 +9,10 @@ public class UseLocalTime {
|
|||
return LocalTime.of(hour, min, seconds);
|
||||
}
|
||||
|
||||
LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min) {
|
||||
return LocalTime.of(hour, min);
|
||||
}
|
||||
|
||||
LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
|
||||
return LocalTime.parse(timeRepresentation);
|
||||
}
|
|
@ -12,31 +12,35 @@ class UseZonedDateTime {
|
|||
return ZonedDateTime.of(localDateTime, zoneId);
|
||||
}
|
||||
|
||||
ZonedDateTime getZonedDateTimeUsingParseMethod(String parsableString) {
|
||||
return ZonedDateTime.parse(parsableString);
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDay(LocalDate localDate, ZoneId zone) {
|
||||
ZonedDateTime startofDay = localDate.atStartOfDay()
|
||||
ZonedDateTime startOfDay = localDate.atStartOfDay()
|
||||
.atZone(zone);
|
||||
return startofDay;
|
||||
return startOfDay;
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDayShorthand(LocalDate localDate, ZoneId zone) {
|
||||
ZonedDateTime startofDay = localDate.atStartOfDay(zone);
|
||||
return startofDay;
|
||||
ZonedDateTime startOfDay = localDate.atStartOfDay(zone);
|
||||
return startOfDay;
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDayFromZonedDateTime(ZonedDateTime zonedDateTime) {
|
||||
ZonedDateTime startofDay = zonedDateTime.toLocalDateTime()
|
||||
ZonedDateTime startOfDay = zonedDateTime.toLocalDateTime()
|
||||
.toLocalDate()
|
||||
.atStartOfDay(zonedDateTime.getZone());
|
||||
return startofDay;
|
||||
return startOfDay;
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDayAtMinTime(ZonedDateTime zonedDateTime) {
|
||||
ZonedDateTime startofDay = zonedDateTime.with(ChronoField.HOUR_OF_DAY, 0);
|
||||
return startofDay;
|
||||
ZonedDateTime startOfDay = zonedDateTime.with(ChronoField.HOUR_OF_DAY, 0);
|
||||
return startOfDay;
|
||||
}
|
||||
|
||||
ZonedDateTime getStartOfDayAtMidnightTime(ZonedDateTime zonedDateTime) {
|
||||
ZonedDateTime startofDay = zonedDateTime.with(ChronoField.NANO_OF_DAY, 0);
|
||||
return startofDay;
|
||||
ZonedDateTime startOfDay = zonedDateTime.with(ChronoField.NANO_OF_DAY, 0);
|
||||
return startOfDay;
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
|
@ -1,12 +1,16 @@
|
|||
package com.baeldung.date.comparison;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.*;
|
||||
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class Java8DateTimeApiGeneralComparisonsUnitTest {
|
||||
|
||||
@Test
|
||||
|
@ -54,10 +58,8 @@ public class Java8DateTimeApiGeneralComparisonsUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenZonedDateTimes_whenComparing_thenAssertsPass() {
|
||||
ZonedDateTime timeInNewYork = ZonedDateTime.of(2019, 8, 10, 8, 0, 0, 0,
|
||||
ZoneId.of("America/New_York"));
|
||||
ZonedDateTime timeInBerlin = ZonedDateTime.of(2019, 8, 10, 14, 0, 0, 0,
|
||||
ZoneId.of("Europe/Berlin"));
|
||||
ZonedDateTime timeInNewYork = ZonedDateTime.of(2019, 8, 10, 8, 0, 0, 0, ZoneId.of("America/New_York"));
|
||||
ZonedDateTime timeInBerlin = ZonedDateTime.of(2019, 8, 10, 14, 0, 0, 0, ZoneId.of("Europe/Berlin"));
|
||||
|
||||
assertThat(timeInNewYork.isAfter(timeInBerlin), is(false));
|
||||
assertThat(timeInNewYork.isBefore(timeInBerlin), is(false));
|
||||
|
@ -80,4 +82,14 @@ public class Java8DateTimeApiGeneralComparisonsUnitTest {
|
|||
|
||||
assertThat(firstTime.compareTo(secondTime), is(-1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMinMaxLocalTimes_whenComparing_thenAssertsPass() {
|
||||
LocalTime minTime = LocalTime.MIN;
|
||||
LocalTime time = LocalTime.of(8, 30);
|
||||
LocalTime maxTime = LocalTime.MAX;
|
||||
|
||||
assertThat(minTime.isBefore(time), is(true));
|
||||
assertThat(time.isBefore(maxTime), is(true));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package com.baeldung.dateapi;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class JavaDurationUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenATimePlus30Seconds_whenRequestingDuration_thenExpect30() {
|
||||
LocalTime initialTime = LocalTime.of(6, 30, 0);
|
||||
LocalTime finalTime = initialTime.plus(Duration.ofSeconds(30));
|
||||
|
||||
long seconds = Duration.between(initialTime, finalTime)
|
||||
.getSeconds();
|
||||
|
||||
assertThat(seconds).isEqualTo(30);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenATimePlus30Seconds_whenRequestingSecondsBetween_thenExpect30() {
|
||||
LocalTime initialTime = LocalTime.of(6, 30, 0);
|
||||
LocalTime finalTime = initialTime.plus(Duration.ofSeconds(30));
|
||||
|
||||
long seconds = ChronoUnit.SECONDS.between(initialTime, finalTime);
|
||||
|
||||
assertThat(seconds).isEqualTo(30);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void test2() {
|
||||
Instant start = Instant.parse("2017-10-03T10:15:30.00Z");
|
||||
Instant end = Instant.parse("2017-10-03T10:16:30.00Z");
|
||||
|
||||
Duration duration = Duration.between(start, end);
|
||||
|
||||
assertFalse(duration.isNegative());
|
||||
|
||||
assertEquals(60, duration.getSeconds());
|
||||
assertEquals(1, duration.toMinutes());
|
||||
|
||||
Duration fromDays = Duration.ofDays(1);
|
||||
assertEquals(86400, fromDays.getSeconds());
|
||||
|
||||
Duration fromMinutes = Duration.ofMinutes(60);
|
||||
assertEquals(1, fromMinutes.toHours());
|
||||
|
||||
assertEquals(120, duration.plusSeconds(60)
|
||||
.getSeconds());
|
||||
assertEquals(30, duration.minusSeconds(30)
|
||||
.getSeconds());
|
||||
|
||||
assertEquals(120, duration.plus(60, ChronoUnit.SECONDS)
|
||||
.getSeconds());
|
||||
assertEquals(30, duration.minus(30, ChronoUnit.SECONDS)
|
||||
.getSeconds());
|
||||
|
||||
Duration fromChar1 = Duration.parse("P1DT1H10M10.5S");
|
||||
Duration fromChar2 = Duration.parse("PT10M");
|
||||
}
|
||||
|
||||
}
|
|
@ -1,18 +1,41 @@
|
|||
package com.baeldung.dateapi;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Period;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class JavaPeriodUnitTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(JavaPeriodUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void givenADatePlus5Days_whenRequestingPeriod_thenExpectFive() {
|
||||
LocalDate initialDate = LocalDate.parse("2007-05-10");
|
||||
LocalDate finalDate = initialDate.plus(Period.ofDays(5));
|
||||
|
||||
int days = Period.between(initialDate, finalDate)
|
||||
.getDays();
|
||||
|
||||
assertThat(days).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenADatePlus5Days_whenRequestingDaysBetween_thenExpectFive() {
|
||||
LocalDate initialDate = LocalDate.parse("2007-05-10");
|
||||
LocalDate finalDate = initialDate.plus(Period.ofDays(5));
|
||||
|
||||
long days = ChronoUnit.DAYS.between(initialDate, finalDate);
|
||||
|
||||
assertThat(days).isEqualTo(5);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTestPeriod_thenOk() {
|
||||
|
||||
|
@ -24,8 +47,10 @@ public class JavaPeriodUnitTest {
|
|||
LOG.info(String.format("Years:%d months:%d days:%d", period.getYears(), period.getMonths(), period.getDays()));
|
||||
|
||||
assertFalse(period.isNegative());
|
||||
assertEquals(56, period.plusDays(50).getDays());
|
||||
assertEquals(9, period.minusMonths(2).getMonths());
|
||||
assertEquals(56, period.plusDays(50)
|
||||
.getDays());
|
||||
assertEquals(9, period.minusMonths(2)
|
||||
.getMonths());
|
||||
|
||||
Period fromUnits = Period.of(3, 10, 10);
|
||||
Period fromDays = Period.ofDays(50);
|
|
@ -7,12 +7,13 @@ import java.time.LocalDate;
|
|||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.Month;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class UseLocalDateTimeUnitTest {
|
||||
|
||||
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
||||
private UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingParse_thenLocalDateTime() {
|
||||
|
@ -33,4 +34,28 @@ public class UseLocalDateTimeUnitTest {
|
|||
assertThat(endOfDayFromGivenDirectly.toLocalTime()).isEqualTo(LocalTime.MAX);
|
||||
assertThat(endOfDayFromGivenDirectly.toString()).isEqualTo("2018-06-23T23:59:59.999999999");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTimeInFebruary_whenRequestingMonth_thenMonthIsFebruary() {
|
||||
LocalDateTime givenLocalDateTime = LocalDateTime.of(2015, Month.FEBRUARY, 20, 6, 30);
|
||||
|
||||
assertThat(givenLocalDateTime.getMonth()).isEqualTo(Month.FEBRUARY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTime_whenManipulating_thenResultIsAsExpected() {
|
||||
LocalDateTime givenLocalDateTime = LocalDateTime.parse("2015-02-20T06:30:00");
|
||||
|
||||
LocalDateTime manipulatedLocalDateTime = givenLocalDateTime.plusDays(1);
|
||||
manipulatedLocalDateTime = manipulatedLocalDateTime.minusHours(2);
|
||||
|
||||
assertThat(manipulatedLocalDateTime).isEqualTo(LocalDateTime.of(2015, Month.FEBRUARY, 21, 4, 30));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestTimeFromEpoch_thenResultIsAsExpected() {
|
||||
LocalDateTime result = useLocalDateTime.ofEpochSecond(1465817690, ZoneOffset.UTC);
|
||||
|
||||
assertThat(result.toString()).isEqualTo("2016-06-13T11:34:50");
|
||||
}
|
||||
}
|
|
@ -12,7 +12,7 @@ import org.junit.Test;
|
|||
|
||||
public class UseLocalDateUnitTest {
|
||||
|
||||
UseLocalDate useLocalDate = new UseLocalDate();
|
||||
private UseLocalDate useLocalDate = new UseLocalDate();
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingFactoryOf_thenLocalDate() {
|
||||
|
@ -88,4 +88,31 @@ public class UseLocalDateUnitTest {
|
|||
assertThat(endOfDayWithMax.toString()).isEqualTo("2018-06-23T23:59:59.999999999");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTheYear2000_whenCheckingForLeapYear_thenReturnTrue() {
|
||||
LocalDate given = LocalDate.parse("2000-06-23");
|
||||
|
||||
boolean leapYear = useLocalDate.isLeapYear(given);
|
||||
|
||||
assertThat(leapYear).isEqualTo(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTheYear2004_whenCheckingForLeapYear_thenReturnTrue() {
|
||||
LocalDate given = LocalDate.parse("2004-06-23");
|
||||
|
||||
boolean leapYear = useLocalDate.isLeapYear(given);
|
||||
|
||||
assertThat(leapYear).isEqualTo(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTheYear2019_whenCheckingForLeapYear_thenReturnFalse() {
|
||||
LocalDate given = LocalDate.parse("2019-06-23");
|
||||
|
||||
boolean leapYear = useLocalDate.isLeapYear(given);
|
||||
|
||||
assertThat(leapYear).isEqualTo(false);
|
||||
}
|
||||
|
||||
}
|
|
@ -7,21 +7,30 @@ import org.junit.Test;
|
|||
|
||||
public class UseLocalTimeUnitTest {
|
||||
|
||||
UseLocalTime useLocalTime = new UseLocalTime();
|
||||
private UseLocalTime useLocalTime = new UseLocalTime();
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingFactoryOf_thenLocalTime() {
|
||||
Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7).toString());
|
||||
Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7)
|
||||
.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValues_whenUsingFactoryOfWithoutSeconds_thenLocalTime() {
|
||||
Assert.assertEquals("07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7)
|
||||
.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_whenUsingParse_thenLocalTime() {
|
||||
Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30").toString());
|
||||
Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30")
|
||||
.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTime_whenAddHour_thenLocalTime() {
|
||||
Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)).toString());
|
||||
Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30))
|
||||
.toString());
|
||||
}
|
||||
|
||||
@Test
|
|
@ -1,72 +1,72 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.DateTimeZone;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UseTimeZoneUnitTest {
|
||||
|
||||
/* https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */
|
||||
|
||||
String timeZone = "Asia/Singapore";
|
||||
|
||||
private static final String PATTERN = "E yyyy-MM-dd HH:mm:ss a";
|
||||
|
||||
@Test
|
||||
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava7_ThenTimeZoneIsSetSuccessfully() {
|
||||
Date nowUtc = new Date();
|
||||
TimeZone asiaSingapore = TimeZone.getTimeZone(timeZone);
|
||||
|
||||
Calendar nowAsiaSingapore = Calendar.getInstance(asiaSingapore);
|
||||
nowAsiaSingapore.setTime(nowUtc);
|
||||
|
||||
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN);
|
||||
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
|
||||
|
||||
System.out.println(String.format("Java7: Time now in '%s' is '%s'", nowAsiaSingapore.getTimeZone()
|
||||
.getID(), simpleDateFormat.format(nowAsiaSingapore.getTime())));
|
||||
|
||||
Assert.assertEquals(nowUtc.toInstant().getEpochSecond(), nowAsiaSingapore.toInstant().getEpochSecond());
|
||||
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getTimeZone());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava8_ThenTimeZoneIsSetSuccessfully() {
|
||||
Instant nowUtc = Instant.now();
|
||||
ZoneId asiaSingapore = ZoneId.of(timeZone);
|
||||
|
||||
ZonedDateTime nowAsiaSingapore = ZonedDateTime.ofInstant(nowUtc, asiaSingapore);
|
||||
|
||||
System.out.println(String.format("Java8: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(),
|
||||
nowAsiaSingapore.format(DateTimeFormatter.ofPattern(PATTERN))));
|
||||
|
||||
Assert.assertEquals(nowUtc.getEpochSecond(), nowAsiaSingapore.toEpochSecond());
|
||||
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJodaTime_ThenTimeZoneIsSetSuccessfully() {
|
||||
org.joda.time.Instant nowUtc = org.joda.time.Instant.now();
|
||||
DateTimeZone asiaSingapore = DateTimeZone.forID(timeZone);
|
||||
|
||||
DateTime nowAsiaSingapore = nowUtc.toDateTime(asiaSingapore);
|
||||
|
||||
System.out.println(String.format("Joda-time: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(),
|
||||
nowAsiaSingapore.toString(PATTERN)));
|
||||
|
||||
Assert.assertEquals(nowUtc.toInstant().getMillis(), nowAsiaSingapore.toInstant().getMillis());
|
||||
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone());
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.datetime;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.DateTimeZone;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UseTimeZoneUnitTest {
|
||||
|
||||
/* https://en.wikipedia.org/wiki/List_of_tz_database_time_zones */
|
||||
|
||||
String timeZone = "Asia/Singapore";
|
||||
|
||||
private static final String PATTERN = "E yyyy-MM-dd HH:mm:ss a";
|
||||
|
||||
@Test
|
||||
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava7_ThenTimeZoneIsSetSuccessfully() {
|
||||
Date nowUtc = new Date();
|
||||
TimeZone asiaSingapore = TimeZone.getTimeZone(timeZone);
|
||||
|
||||
Calendar nowAsiaSingapore = Calendar.getInstance(asiaSingapore);
|
||||
nowAsiaSingapore.setTime(nowUtc);
|
||||
|
||||
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(PATTERN);
|
||||
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
|
||||
|
||||
System.out.println(String.format("Java7: Time now in '%s' is '%s'", nowAsiaSingapore.getTimeZone()
|
||||
.getID(), simpleDateFormat.format(nowAsiaSingapore.getTime())));
|
||||
|
||||
Assert.assertEquals(nowUtc.toInstant().getEpochSecond(), nowAsiaSingapore.toInstant().getEpochSecond());
|
||||
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getTimeZone());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJava8_ThenTimeZoneIsSetSuccessfully() {
|
||||
Instant nowUtc = Instant.now();
|
||||
ZoneId asiaSingapore = ZoneId.of(timeZone);
|
||||
|
||||
ZonedDateTime nowAsiaSingapore = ZonedDateTime.ofInstant(nowUtc, asiaSingapore);
|
||||
|
||||
System.out.println(String.format("Java8: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(),
|
||||
nowAsiaSingapore.format(DateTimeFormatter.ofPattern(PATTERN))));
|
||||
|
||||
Assert.assertEquals(nowUtc.getEpochSecond(), nowAsiaSingapore.toEpochSecond());
|
||||
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDateWithoutTimeZone_WhenSetTimeZoneUsingJodaTime_ThenTimeZoneIsSetSuccessfully() {
|
||||
org.joda.time.Instant nowUtc = org.joda.time.Instant.now();
|
||||
DateTimeZone asiaSingapore = DateTimeZone.forID(timeZone);
|
||||
|
||||
DateTime nowAsiaSingapore = nowUtc.toDateTime(asiaSingapore);
|
||||
|
||||
System.out.println(String.format("Joda-time: Time now in '%s' is '%s'", nowAsiaSingapore.getZone(),
|
||||
nowAsiaSingapore.toString(PATTERN)));
|
||||
|
||||
Assert.assertEquals(nowUtc.toInstant().getMillis(), nowAsiaSingapore.toInstant().getMillis());
|
||||
Assert.assertEquals(asiaSingapore, nowAsiaSingapore.getZone());
|
||||
}
|
||||
|
||||
}
|
|
@ -7,13 +7,14 @@ import java.time.LocalDateTime;
|
|||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UseZonedDateTimeUnitTest {
|
||||
|
||||
UseZonedDateTime zonedDateTime = new UseZonedDateTime();
|
||||
private UseZonedDateTime zonedDateTime = new UseZonedDateTime();
|
||||
|
||||
@Test
|
||||
public void givenZoneId_thenZonedDateTime() {
|
||||
|
@ -22,6 +23,13 @@ public class UseZonedDateTimeUnitTest {
|
|||
Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRequestingZones_thenAtLeastOneIsReturned() {
|
||||
Set<String> allZoneIds = ZoneId.getAvailableZoneIds();
|
||||
|
||||
assertThat(allZoneIds.size()).isGreaterThan(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateOrZoned_whenSettingStartOfDay_thenReturnMidnightInAllCases() {
|
||||
LocalDate given = LocalDate.parse("2018-06-23");
|
||||
|
@ -42,4 +50,15 @@ public class UseZonedDateTimeUnitTest {
|
|||
assertThat(startOfOfDayWithMethod.toLocalTime()
|
||||
.toString()).isEqualTo("00:00");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAStringWithTimeZone_whenParsing_thenEqualsExpected() {
|
||||
ZonedDateTime resultFromString = zonedDateTime.getZonedDateTimeUsingParseMethod("2015-05-03T10:15:30+01:00[Europe/Paris]");
|
||||
ZonedDateTime resultFromLocalDateTime = ZonedDateTime.of(2015, 5, 3, 11, 15, 30, 0, ZoneId.of("Europe/Paris"));
|
||||
|
||||
assertThat(resultFromString.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));
|
||||
assertThat(resultFromLocalDateTime.getZone()).isEqualTo(ZoneId.of("Europe/Paris"));
|
||||
|
||||
assertThat(resultFromString).isEqualTo(resultFromLocalDateTime);
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue