Merge branch 'master' into master
This commit is contained in:
@@ -4,3 +4,7 @@
|
||||
|
||||
- [JDBC with Groovy](http://www.baeldung.com/jdbc-groovy)
|
||||
- [Working with JSON in Groovy](http://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)
|
||||
|
||||
+12
-3
@@ -23,6 +23,12 @@
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>${groovy-all.version}</version>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-dateutil</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
@@ -103,9 +109,12 @@
|
||||
|
||||
<properties>
|
||||
<junit.platform.version>1.0.0</junit.platform.version>
|
||||
<groovy.version>2.4.13</groovy.version>
|
||||
<groovy-all.version>2.4.13</groovy-all.version>
|
||||
<groovy-sql.version>2.4.13</groovy-sql.version>
|
||||
<!-- <groovy.version>2.4.13</groovy.version> -->
|
||||
<!-- <groovy-all.version>2.4.13</groovy-all.version> -->
|
||||
<!-- <groovy-sql.version>2.4.13</groovy-sql.version> -->
|
||||
<groovy.version>2.5.6</groovy.version>
|
||||
<groovy-all.version>2.5.6</groovy-all.version>
|
||||
<groovy-sql.version>2.5.6</groovy-sql.version>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.groovy.sql
|
||||
|
||||
import static org.junit.Assert.*
|
||||
import java.util.Calendar.*
|
||||
import java.time.LocalDate
|
||||
import java.text.SimpleDateFormat
|
||||
import org.junit.Test
|
||||
|
||||
|
||||
class DateTest {
|
||||
|
||||
def dateStr = "2019-02-28"
|
||||
def pattern = "yyyy-MM-dd"
|
||||
|
||||
@Test
|
||||
void whenGetStringRepresentation_thenCorrectlyConvertIntoDate() {
|
||||
def dateFormat = new SimpleDateFormat(pattern)
|
||||
def date = dateFormat.parse(dateStr)
|
||||
|
||||
println(" String to Date with DateFormatter : " + date)
|
||||
|
||||
def cal = new GregorianCalendar();
|
||||
cal.setTime(date);
|
||||
|
||||
assertEquals(cal.get(Calendar.YEAR),2019)
|
||||
assertEquals(cal.get(Calendar.DAY_OF_MONTH),28)
|
||||
assertEquals(cal.get(Calendar.MONTH),java.util.Calendar.FEBRUARY)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenGetStringRepresentation_thenCorrectlyConvertWithDateUtilsExtension() {
|
||||
|
||||
def date = Date.parse(pattern, dateStr)
|
||||
|
||||
println(" String to Date with Date.parse : " + date)
|
||||
|
||||
def cal = new GregorianCalendar();
|
||||
cal.setTime(date);
|
||||
|
||||
assertEquals(cal.get(Calendar.YEAR),2019)
|
||||
assertEquals(cal.get(Calendar.DAY_OF_MONTH),28)
|
||||
assertEquals(cal.get(Calendar.MONTH),java.util.Calendar.FEBRUARY)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenGetStringRepresentation_thenCorrectlyConvertIntoDateWithLocalDate() {
|
||||
def date = LocalDate.parse(dateStr, pattern)
|
||||
|
||||
println(" String to Date with LocalDate : " + date)
|
||||
|
||||
assertEquals(date.getYear(),2019)
|
||||
assertEquals(date.getMonth(),java.time.Month.FEBRUARY)
|
||||
assertEquals(date.getDayOfMonth(),28)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -38,3 +38,4 @@
|
||||
- [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs)
|
||||
- [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated)
|
||||
- [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain)
|
||||
- [Method References in Java](https://www.baeldung.com/java-method-references)
|
||||
|
||||
@@ -27,3 +27,5 @@
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
|
||||
- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set)
|
||||
- [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)
|
||||
|
||||
@@ -28,3 +28,5 @@
|
||||
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
|
||||
- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
|
||||
- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal)
|
||||
- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int)
|
||||
- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance)
|
||||
|
||||
@@ -32,3 +32,4 @@
|
||||
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
|
||||
- [Differences Between HashMap and Hashtable](https://www.baeldung.com/hashmap-hashtable-differences)
|
||||
- [Java ArrayList vs Vector](https://www.baeldung.com/java-arraylist-vs-vector)
|
||||
- [Defining a Char Stack in Java](https://www.baeldung.com/java-char-stack)
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.java.sort;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class CollectionsSortCompare {
|
||||
|
||||
public static void main(String[] args) {
|
||||
sortPrimitives();
|
||||
sortReferenceType();
|
||||
sortCollection();
|
||||
}
|
||||
|
||||
private static void sortReferenceType() {
|
||||
Integer[] numbers = {5, 22, 10, 0};
|
||||
Arrays.sort(numbers);
|
||||
System.out.println(Arrays.toString(numbers));
|
||||
}
|
||||
|
||||
private static void sortCollection() {
|
||||
List<Integer> numbersList = new ArrayList<>();
|
||||
numbersList.add(5);
|
||||
numbersList.add(22);
|
||||
numbersList.add(10);
|
||||
numbersList.add(0);
|
||||
|
||||
Collections.sort(numbersList);
|
||||
|
||||
numbersList.forEach(System.out::print);
|
||||
}
|
||||
|
||||
private static void sortPrimitives() {
|
||||
int[] numbers = {5, 22, 10, 0};
|
||||
Arrays.sort(numbers);
|
||||
System.out.println(Arrays.toString(numbers));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.SingleShotTime)
|
||||
@OutputTimeUnit(TimeUnit.MILLISECONDS)
|
||||
@Measurement(batchSize = 100000, iterations = 10)
|
||||
@Warmup(batchSize = 100000, iterations = 10)
|
||||
public class ArraySortBenchmark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class Initialize {
|
||||
Integer[] numbers = {5, 22, 10, 0};
|
||||
int[] primitives = {5, 22, 10, 0};
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Integer[] benchmarkArraysIntegerSort(ArraySortBenchmark.Initialize state) {
|
||||
Arrays.sort(state.numbers);
|
||||
return state.numbers;
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int[] benchmarkArraysIntSort(ArraySortBenchmark.Initialize state) {
|
||||
Arrays.sort(state.primitives);
|
||||
return state.primitives;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(ArraySortBenchmark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
||||
@@ -22,3 +22,4 @@
|
||||
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
|
||||
- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors)
|
||||
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
|
||||
- [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces)
|
||||
|
||||
@@ -41,3 +41,4 @@
|
||||
- [Java Interfaces](https://www.baeldung.com/java-interfaces)
|
||||
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
|
||||
- [Variable Scope in Java](https://www.baeldung.com/java-variable-scope)
|
||||
- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects)
|
||||
|
||||
@@ -14,3 +14,4 @@
|
||||
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
|
||||
- [Guide to Java URL Encoding/Decoding](http://www.baeldung.com/java-url-encoding-decoding)
|
||||
- [Do a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
|
||||
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
|
||||
+1
-1
@@ -19,7 +19,6 @@
|
||||
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
|
||||
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
|
||||
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
|
||||
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
|
||||
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
|
||||
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
|
||||
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
||||
@@ -51,3 +50,4 @@
|
||||
- [Using Curl in Java](https://www.baeldung.com/java-curl)
|
||||
- [Finding Leap Years in Java](https://www.baeldung.com/java-leap-year)
|
||||
- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators)
|
||||
- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.urlconnection;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
public class PostJSONWithHttpURLConnection {
|
||||
|
||||
public static void main (String []args) throws IOException{
|
||||
//Change the URL with any other publicly accessible POST resource, which accepts JSON request body
|
||||
URL url = new URL ("https://reqres.in/api/users");
|
||||
|
||||
HttpURLConnection con = (HttpURLConnection)url.openConnection();
|
||||
con.setRequestMethod("POST");
|
||||
|
||||
con.setRequestProperty("Content-Type", "application/json; utf-8");
|
||||
con.setRequestProperty("Accept", "application/json");
|
||||
|
||||
con.setDoOutput(true);
|
||||
|
||||
//JSON String need to be constructed for the specific resource.
|
||||
//We may construct complex JSON using any third-party JSON libraries such as jackson or org.json
|
||||
String jsonInputString = "{\"name\": \"Upendra\", \"job\": \"Programmer\"}";
|
||||
|
||||
try(OutputStream os = con.getOutputStream()){
|
||||
byte[] input = jsonInputString.getBytes("utf-8");
|
||||
os.write(input, 0, input.length);
|
||||
}
|
||||
|
||||
int code = con.getResponseCode();
|
||||
System.out.println(code);
|
||||
|
||||
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
|
||||
StringBuilder response = new StringBuilder();
|
||||
String responseLine = null;
|
||||
while ((responseLine = br.readLine()) != null) {
|
||||
response.append(responseLine.trim());
|
||||
}
|
||||
System.out.println(response.toString());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Void Type in Kotlin](https://www.baeldung.com/kotlin-void-type)
|
||||
- [How to use Kotlin Range Expressions](https://www.baeldung.com/kotlin-ranges)
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package stringcomparison
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class StringComparisonUnitTest {
|
||||
|
||||
@Test
|
||||
fun `compare using equals operator`() {
|
||||
val first = "kotlin"
|
||||
val second = "kotlin"
|
||||
val firstCapitalized = "KOTLIN"
|
||||
assertTrue { first == second }
|
||||
assertFalse { first == firstCapitalized }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `compare using referential equals operator`() {
|
||||
val first = "kotlin"
|
||||
val second = "kotlin"
|
||||
val copyOfFirst = buildString { "kotlin" }
|
||||
assertTrue { first === second }
|
||||
assertFalse { first === copyOfFirst }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `compare using equals method`() {
|
||||
val first = "kotlin"
|
||||
val second = "kotlin"
|
||||
val firstCapitalized = "KOTLIN"
|
||||
assertTrue { first.equals(second) }
|
||||
assertFalse { first.equals(firstCapitalized) }
|
||||
assertTrue { first.equals(firstCapitalized, true) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `compare using compare method`() {
|
||||
val first = "kotlin"
|
||||
val second = "kotlin"
|
||||
val firstCapitalized = "KOTLIN"
|
||||
assertTrue { first.compareTo(second) == 0 }
|
||||
assertTrue { first.compareTo(firstCapitalized) == 32 }
|
||||
assertTrue { firstCapitalized.compareTo(first) == -32 }
|
||||
assertTrue { first.compareTo(firstCapitalized, true) == 0 }
|
||||
}
|
||||
}
|
||||
@@ -52,3 +52,5 @@
|
||||
- [Inline Classes in Kotlin](https://www.baeldung.com/kotlin-inline-classes)
|
||||
- [Creating Java static final Equivalents in Kotlin](https://www.baeldung.com/kotlin-java-static-final)
|
||||
- [Nested forEach in Kotlin](https://www.baeldung.com/kotlin-nested-foreach)
|
||||
- [Building DSLs in Kotlin](https://www.baeldung.com/kotlin-dsl)
|
||||
- [Static Methods Behavior in Kotlin](https://www.baeldung.com/kotlin-static-methods)
|
||||
|
||||
@@ -33,24 +33,11 @@
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>maven2-repository.dev.java.net</id>
|
||||
<name>Java.net repository</name>
|
||||
<url>http://download.java.net/maven/2</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>osgeo</id>
|
||||
<name>Open Source Geospatial Foundation Repository</name>
|
||||
<url>http://download.osgeo.org/webdav/geotools/</url>
|
||||
</repository>
|
||||
<repository>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
<id>opengeo</id>
|
||||
<name>OpenGeo Maven Repository</name>
|
||||
<url>http://repo.opengeo.org</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
|
||||
@@ -10,3 +10,4 @@
|
||||
- [Save Data to a JSON File with Gson](https://www.baeldung.com/gson-save-file)
|
||||
- [Convert JSON to a Map Using Gson](https://www.baeldung.com/gson-json-to-map)
|
||||
- [Working with Primitive Values in Gson](https://www.baeldung.com/java-gson-primitives)
|
||||
- [Convert String to JsonObject with Gson](https://www.baeldung.com/gson-string-to-jsonobject)
|
||||
|
||||
@@ -2,3 +2,4 @@
|
||||
|
||||
### Relevant Articles
|
||||
- [Guide to Google Guice](http://www.baeldung.com/guice)
|
||||
- [Guice vs Spring – Dependency Injection](https://www.baeldung.com/guice-spring-dependency-injection)
|
||||
|
||||
@@ -20,3 +20,4 @@
|
||||
- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps)
|
||||
- [Immutable Map Implementations in Java](https://www.baeldung.com/java-immutable-maps)
|
||||
- [Map to String Conversion in Java](https://www.baeldung.com/java-map-to-string-conversion)
|
||||
- [Guide to Apache Commons MultiValuedMap](https://www.baeldung.com/apache-commons-multi-valued-map)
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.reduce.application;
|
||||
|
||||
import com.baeldung.reduce.entities.User;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Fork;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.Warmup;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
int result1 = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
|
||||
System.out.println(result1);
|
||||
|
||||
int result2 = numbers.stream().reduce(0, Integer::sum);
|
||||
System.out.println(result2);
|
||||
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result3 = letters.stream().reduce("", (partialString, element) -> partialString + element);
|
||||
System.out.println(result3);
|
||||
|
||||
String result4 = letters.stream().reduce("", String::concat);
|
||||
System.out.println(result4);
|
||||
|
||||
String result5 = letters.stream().reduce("", (partialString, element) -> partialString.toUpperCase() + element.toUpperCase());
|
||||
System.out.println(result5);
|
||||
|
||||
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
||||
int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
System.out.println(result6);
|
||||
|
||||
String result7 = letters.parallelStream().reduce("", String::concat);
|
||||
System.out.println(result7);
|
||||
|
||||
int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
System.out.println(result8);
|
||||
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@Fork(value = 1, warmups = 2)
|
||||
@Warmup(iterations = 2)
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public void executeReduceOnParallelizedStream() {
|
||||
List<User> userList = new ArrayList<>();
|
||||
for (int i = 0; i <= 1000000; i++) {
|
||||
userList.add(new User("John" + i, i));
|
||||
}
|
||||
userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@Fork(value = 1, warmups = 2)
|
||||
@Warmup(iterations = 2)
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
public void executeReduceOnSequentialStream() {
|
||||
List<User> userList = new ArrayList<>();
|
||||
for (int i = 0; i <= 1000000; i++) {
|
||||
userList.add(new User("John" + i, i));
|
||||
}
|
||||
userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.reduce.entities;
|
||||
|
||||
public class User {
|
||||
|
||||
private final String name;
|
||||
private final int age;
|
||||
|
||||
public User(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "name=" + name + ", age=" + age + '}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.reduce.utilities;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public abstract class NumberUtils {
|
||||
|
||||
private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName());
|
||||
|
||||
public static int divideListElements(List<Integer> values, Integer divider) {
|
||||
return values.stream()
|
||||
.reduce(0, (a, b) -> {
|
||||
try {
|
||||
return a / divider + b / divider;
|
||||
} catch (ArithmeticException e) {
|
||||
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
public static int divideListElementsWithExtractedTryCatchBlock(List<Integer> values, int divider) {
|
||||
return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider));
|
||||
}
|
||||
|
||||
public static int divideListElementsWithApplyFunctionMethod(List<Integer> values, int divider) {
|
||||
BiFunction<Integer, Integer, Integer> division = (a, b) -> a / b;
|
||||
return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider));
|
||||
}
|
||||
|
||||
private static int divide(int value, int factor) {
|
||||
int result = 0;
|
||||
try {
|
||||
result = value / factor;
|
||||
} catch (ArithmeticException e) {
|
||||
LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int applyFunction(BiFunction<Integer, Integer, Integer> function, int a, int b) {
|
||||
try {
|
||||
return function.apply(a, b);
|
||||
}
|
||||
catch(Exception e) {
|
||||
LOGGER.log(Level.INFO, "Exception occurred!");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.reduce.tests;
|
||||
|
||||
import com.baeldung.reduce.entities.User;
|
||||
import com.baeldung.reduce.utilities.NumberUtils;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import org.junit.Test;
|
||||
|
||||
public class StreamReduceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
int result = numbers.stream().reduce(0, (a, b) -> a + b);
|
||||
assertThat(result).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
int result = numbers.stream().reduce(0, Integer::sum);
|
||||
assertThat(result).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.stream().reduce("", (a, b) -> a + b);
|
||||
assertThat(result).isEqualTo("abcde");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.stream().reduce("", String::concat);
|
||||
assertThat(result).isEqualTo("abcde");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase());
|
||||
assertThat(result).isEqualTo("ABCDE");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
|
||||
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
|
||||
int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
assertThat(result).isEqualTo(65);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStringList_whenReduceWithParallelStream_thenCorrect() {
|
||||
List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
|
||||
String result = letters.parallelStream().reduce("", String::concat);
|
||||
assertThat(result).isEqualTo("abcde");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
}
|
||||
@@ -53,3 +53,4 @@
|
||||
- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions)
|
||||
- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram)
|
||||
- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words)
|
||||
- [Common String Operations in Java](https://www.baeldung.com/java-string-operations)
|
||||
|
||||
@@ -3,3 +3,4 @@
|
||||
- [JHipster with a Microservice Architecture](http://www.baeldung.com/jhipster-microservices)
|
||||
- [Intro to JHipster](http://www.baeldung.com/jhipster)
|
||||
- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service)
|
||||
- [Creating New Roles and Authorities in JHipster](https://www.baeldung.com/jhipster-new-roles)
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
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.jhipster</groupId>
|
||||
<artifactId>jhipster-microservice-uaa</artifactId>
|
||||
<name>JHipster Microservice with UAA</name>
|
||||
<artifactId>jhipster-uaa</artifactId>
|
||||
<name>jhipster-uaa</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<parent>
|
||||
|
||||
@@ -11,3 +11,5 @@
|
||||
- [Overview of JSON Pointer](https://www.baeldung.com/json-pointer)
|
||||
- [Introduction to the JSON Binding API (JSR 367) in Java](http://www.baeldung.com/java-json-binding-api)
|
||||
- [Get a Value by Key in a JSONArray](https://www.baeldung.com/java-jsonarray-get-value-by-key)
|
||||
- [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration)
|
||||
- [Testing Web APIs with Postman Collections](https://www.baeldung.com/postman-testing-collections)
|
||||
|
||||
@@ -66,6 +66,7 @@
|
||||
- [Implementing a FTP-Client in Java](http://www.baeldung.com/java-ftp-client)
|
||||
- [Introduction to Functional Java](https://www.baeldung.com/java-functional-library)
|
||||
- [Intro to Derive4J](https://www.baeldung.com/derive4j)
|
||||
- [A Guide to the Reflections Library](https://www.baeldung.com/reflections-library)
|
||||
|
||||
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user