Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Chirag Dewan 2018-08-07 22:57:01 +05:30
commit 2650a1d5ea
900 changed files with 26940 additions and 1753 deletions

7
.gitignore vendored
View File

@ -56,4 +56,9 @@ core-java-io/hard_link.txt
core-java-io/target_link.txt
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
ethereum/logs/
jmeter/src/main/resources/*-JMeter.csv
jmeter/src/main/resources/*-JMeter.csv
**/node_modules/
**/dist
**/tmp
**/out-tsc

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -23,3 +23,4 @@
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

2
apache-avro/README.md Normal file
View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Guide to Apache Avro](http://www.baeldung.com/java-apache-avro)

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,3 @@
### Relevant Articles:
================================
- [Building a Microservice with Apache Meecrowave](http://www.baeldung.com/apache-meecrowave)

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -8,9 +8,10 @@
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
<artifactId>parent-boot-1</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-1</relativePath>
</parent>
<dependencies>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -10,10 +10,10 @@
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.13.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
<artifactId>parent-boot-1</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-1</relativePath>
</parent>
<dependencies>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -3,3 +3,4 @@
- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference)
- [Guide to Java 10](http://www.baeldung.com/java-10-overview)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -46,7 +46,6 @@
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
- [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection)
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
- [Java Optional orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
@ -55,3 +54,9 @@
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [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)
- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)

View File

@ -99,6 +99,16 @@
<artifactId>joda-time</artifactId>
<version>${joda.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${asspectj.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${asspectj.version}</version>
</dependency>
</dependencies>
<build>
@ -170,6 +180,7 @@
<joda.version>2.10</joda.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<asspectj.version>1.8.9</asspectj.version>
<avaitility.version>1.7.0</avaitility.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version>

View File

@ -0,0 +1,9 @@
package com.baeldung.aspect;
public aspect ChangeCallsToCurrentTimeInMillisMethod {
long around():
call(public static native long java.lang.System.currentTimeMillis())
&& within(user.code.base.pckg.*) {
return 0;
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull {
/**
* This method shows how to make a null safe stream from a collection through the use of
* emptyIfNull() method from Apache Commons CollectionUtils library
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return emptyIfNull(collection).stream();
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingJava8OptionalContainer {
/**
* This method shows how to make a null safe stream from a collection through the use of
* Java SE 8s Optional Container
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return Optional.ofNullable(collection)
.map(Collection::stream)
.orElseGet(Stream::empty);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingNullDereferenceCheck {
/**
* This method shows how to make a null safe stream from a collection through the use of a check
* to prevent null dereferences
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return collection == null ? Stream.empty() : collection.stream();
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

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

View File

@ -0,0 +1,87 @@
package com.baeldung.list;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.*;
public class AddElementsUnitTest {
List<Flower> flowers;
@Before
public void init() {
this.flowers = new ArrayList<>(Arrays.asList(
new Flower("Poppy", 12),
new Flower("Anemone", 8),
new Flower("Catmint", 12)));
}
@Test
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() {
List<Flower> anotherList = new ArrayList<>();
anotherList.addAll(flowers);
assertEquals(anotherList.size(), flowers.size());
Assert.assertTrue(anotherList.containsAll(flowers));
}
@Test
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() {
List<Flower> anotherList = new ArrayList<>();
anotherList.addAll(flowers);
Flower flower = anotherList.get(0);
flower.setPetals(flowers.get(0).getPetals() * 3);
assertEquals(anotherList.size(), flowers.size());
Assert.assertTrue(anotherList.containsAll(flowers));
}
@Test
public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() {
List<Flower> target = new ArrayList<>();
Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0));
assertEquals(target.size(), 4);
}
@Test
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() {
List<Flower> flowerVase = new ArrayList<>();
flowers.stream()
.skip(1)
.forEachOrdered(flowerVase::add);
assertEquals(flowerVase.size() + 1, flowers.size());
assertFalse(flowerVase.containsAll(flowers));
}
@Test
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() {
List<Flower> flowerVase = new ArrayList<>();
flowers.stream()
.filter(f -> f.getPetals() > 10)
.forEachOrdered(flowerVase::add);
assertEquals(flowerVase.size() + 1, flowers.size());
assertFalse(flowerVase.containsAll(flowers));
}
@Test
public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() {
List<Flower> target = new ArrayList<>();
Optional.ofNullable(flowers)
.ifPresent(target::addAll);
assertNotNull(target);
assertEquals(target.size(), 3);
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.*;
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest {
private final NullSafeCollectionStreamsUsingCommonsEmptyIfNull instance =
new NullSafeCollectionStreamsUsingCommonsEmptyIfNull();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@ -0,0 +1,53 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Kwaje Anthony <kwajeanthony@gmail.com>
*/
public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance =
new NullSafeCollectionStreamsUsingJava8OptionalContainer();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Kwaje Anthony <kwajeanthony@gmail.com>
*/
public class NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest {
private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance =
new NullSafeCollectionStreamsUsingNullDereferenceCheck();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@ -1,6 +1,7 @@
package com.baeldung.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.time.Clock;
import java.time.Instant;
@ -9,6 +10,8 @@ import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.junit.Test;
public class CurrentDateTimeUnitTest {
@ -39,5 +42,4 @@ public class CurrentDateTimeUnitTest {
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
}
}

View File

@ -19,11 +19,23 @@
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -50,6 +62,8 @@
<properties>
<!-- testing -->
<assertj.version>3.10.0</assertj.version>
<junit.platform.version>1.2.0</junit.platform.version>
<awaitility.version>1.7.0</awaitility.version>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>

View File

@ -0,0 +1,27 @@
package com.baeldung.java9.language.stream;
import static java.util.stream.Collectors.filtering;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public class StreamsGroupingCollectionFilter {
static public Map<Integer, List<Integer>> findEvenNumbersAfterGroupingByQuantityOfDigits(Collection<Integer> baseCollection) {
Function<Integer, Integer> getQuantityOfDigits = item -> (int) Math.log10(item) + 1;
return baseCollection.stream()
.collect(groupingBy(getQuantityOfDigits, filtering(item -> item % 2 == 0, toList())));
}
static public Map<Integer, List<Integer>> findEvenNumbersBeforeGroupingByQuantityOfDigits(Collection<Integer> baseCollection) {
return baseCollection.stream()
.filter(item -> item % 2 == 0)
.collect(groupingBy(item -> (int) Math.log10(item) + 1, toList()));
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.java9.maps.initialize;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
public class MapsInitializer {
@SuppressWarnings("unused")
public void createMapWithMapOf() {
Map<String, String> emptyMap = Map.of();
Map<String, String> singletonMap = Map.of("key1", "value");
Map<String, String> map = Map.of("key1","value1", "key2", "value2");
}
public void createMapWithMapEntries() {
Map<String, String> map = Map.ofEntries(
new AbstractMap.SimpleEntry<String, String>("name", "John"),
new AbstractMap.SimpleEntry<String, String>("city", "budapest"),
new AbstractMap.SimpleEntry<String, String>("zip", "000000"),
new AbstractMap.SimpleEntry<String, String>("home", "1231231231")
);
}
@SuppressWarnings("unused")
public void createMutableMaps() {
Map<String, String> map = new HashMap<String, String> (Map.of("key1","value1", "key2", "value2"));
Map<String, String> map2 = new HashMap<String, String> ( Map.ofEntries(
new AbstractMap.SimpleEntry<String, String>("name", "John"),
new AbstractMap.SimpleEntry<String, String>("city", "budapest")));
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.java9.language.stream;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
public class CollectionFilterUnitTest {
private static final Collection<Integer> BASE_INTEGER_COLLECTION = Arrays.asList(9, 12, 55, 56, 101, 115, 8002, 223, 2668, 19, 8);
private static final Map<Integer, List<Integer>> EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP = createExpectedFilterAfterGroupingMap();
private static Map<Integer, List<Integer>> createExpectedFilterAfterGroupingMap() {
Map<Integer, List<Integer>> map = new HashMap<>();
map.put(1, Arrays.asList(8));
map.put(2, Arrays.asList(12, 56));
map.put(3, Collections.emptyList());
map.put(4, Arrays.asList(8002, 2668));
return map;
}
private static final Map<Integer, List<Integer>> EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP = createExpectedFilterBeforeGroupingMap();
private static Map<Integer, List<Integer>> createExpectedFilterBeforeGroupingMap() {
Map<Integer, List<Integer>> map = new HashMap<>();
map.put(1, Arrays.asList(8));
map.put(2, Arrays.asList(12, 56));
map.put(4, Arrays.asList(8002, 2668));
return map;
}
@Test
public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() {
Map<Integer, List<Integer>> filteredAfterGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersAfterGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION);
Map<Integer, List<Integer>> filteredBeforeGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersBeforeGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION);
assertThat(filteredAfterGroupingMap).containsAllEntriesOf(EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP);
assertThat(filteredBeforeGroupingMap).doesNotContainKey(3)
.containsAllEntriesOf(EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP);
}
}

View File

@ -30,3 +30,9 @@
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
- [How to Store Duplicate Keys in a Map in Java?](http://www.baeldung.com/java-map-duplicate-keys)
- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size)
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
- [How to Filter a Collection in Java](http://www.baeldung.com/java-collection-filtering)
- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)

View File

@ -36,19 +36,32 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse.collections.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<junit.platform.version>1.2.0</junit.platform.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.6.1</assertj.version>
<eclipse.collections.version>9.2.0</eclipse.collections.version>
</properties>
</project>

View File

@ -1,13 +1,13 @@
package com.baeldung.convertlisttomap;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.MapUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.collections4.MapUtils;
import com.google.common.collect.Maps;
public class ConvertListToMapService {
public Map<Integer, Animal> convertListBeforeJava8(List<Animal> list) {

View File

@ -0,0 +1,16 @@
package com.baeldung.java.filtering;
import java.util.Collection;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
public class CollectionUtilsCollectionFilter {
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> apacheEventNumberPredicate = item -> item % 2 == 0;
CollectionUtils.filter(baseCollection, apacheEventNumberPredicate);
return baseCollection;
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.java.filtering;
import java.util.Collection;
import org.eclipse.collections.api.block.predicate.Predicate;
import org.eclipse.collections.impl.factory.Lists;
import org.eclipse.collections.impl.utility.Iterate;
public class EclipseCollectionsCollectionFilter {
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> eclipsePredicate = item -> item % 2 == 0;
Collection<Integer> filteredList = Lists.mutable.ofAll(baseCollection)
.select(eclipsePredicate);
return filteredList;
}
static public Collection<Integer> findEvenNumbersUsingIterate(Collection<Integer> baseCollection) {
Predicate<Integer> eclipsePredicate = new Predicate<Integer>() {
private static final long serialVersionUID = 1L;
@Override
public boolean accept(Integer arg0) {
return arg0 % 2 == 0;
}
};
Collection<Integer> filteredList = Iterate.select(baseCollection, eclipsePredicate);
return filteredList;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.java.filtering;
import java.util.Collection;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
public class GuavaCollectionFilter {
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> guavaPredicate = item -> item % 2 == 0;
Collection<Integer> filteredCollection = Collections2.filter(baseCollection, guavaPredicate);
return filteredCollection;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.java.filtering;
import java.util.Collection;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class StreamsCollectionFilter {
public static <T> Collection<T> filterCollectionHelperMethod(Collection<T> baseCollection, Predicate<T> predicate) {
return baseCollection.stream()
.filter(predicate)
.collect(Collectors.toList());
}
static public Collection<Integer> findEvenNumbersUsingHelperMethod(Collection<Integer> baseCollection) {
return filterCollectionHelperMethod(baseCollection, item -> item % 2 == 0);
}
static public Collection<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> streamsPredicate = item -> item % 2 == 0;
return baseCollection.stream()
.filter(streamsPredicate)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.java.list;
public class Flower {
private String name;
private int petals;
public Flower(String name, int petals) {
this.name = name;
this.petals = petals;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPetals() {
return petals;
}
public void setPetals(int petals) {
this.petals = petals;
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.java.map.initialize;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MapInitializer {
public static Map<String, String> articleMapOne;
static {
articleMapOne = new HashMap<>();
articleMapOne.put("ar01", "Intro to Map");
articleMapOne.put("ar02", "Some article");
}
public static Map<String, String> createSingletonMap() {
Map<String, String> passwordMap = Collections.singletonMap("username1", "password1");
return passwordMap;
}
public Map<String, String> createEmptyMap() {
Map<String, String> emptyMap = Collections.emptyMap();
return emptyMap;
}
public Map<String, String> createUsingDoubleBrace() {
Map<String, String> doubleBraceMap = new HashMap<String, String>() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
put("key1", "value1");
put("key2", "value2");
}
};
return doubleBraceMap;
}
public Map<String, String> createMapUsingStreamStringArray() {
Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
.collect(Collectors.toMap(data -> data[0], data -> data[1]));
return map;
}
public Map<String, Integer> createMapUsingStreamObjectArray() {
Map<String, Integer> map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, })
.collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1]));
return map;
}
public Map<String, Integer> createMapUsingStreamSimpleEntry() {
Map<String, Integer> map = Stream.of(new AbstractMap.SimpleEntry<>("idea", 1), new AbstractMap.SimpleEntry<>("mobile", 2))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return map;
}
public Map<String, Integer> createMapUsingStreamSimpleImmutableEntry() {
Map<String, Integer> map = Stream.of(new AbstractMap.SimpleImmutableEntry<>("idea", 1), new AbstractMap.SimpleImmutableEntry<>("mobile", 2))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return map;
}
public Map<String, String> createImmutableMapWithStreams() {
Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
.collect(Collectors.collectingAndThen(Collectors.toMap(data -> data[0], data -> data[1]), Collections::<String, String> unmodifiableMap));
return map;
}
}

View File

@ -0,0 +1,111 @@
package com.baeldung.list.removeall;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class RemoveAll {
static void removeWithWhileLoopPrimitiveElement(List<Integer> list, int element) {
while (list.contains(element)) {
list.remove(element);
}
}
static void removeWithWhileLoopNonPrimitiveElement(List<Integer> list, Integer element) {
while (list.contains(element)) {
list.remove(element);
}
}
static void removeWithWhileLoopStoringFirstOccurrenceIndex(List<Integer> list, Integer element) {
int index;
while ((index = list.indexOf(element)) >= 0) {
list.remove(index);
}
}
static void removeWithCallingRemoveUntilModifies(List<Integer> list, Integer element) {
while (list.remove(element))
;
}
static void removeWithStandardForLoopUsingIndex(List<Integer> list, int element) {
for (int i = 0; i < list.size(); i++) {
if (Objects.equals(element, list.get(i))) {
list.remove(i);
}
}
}
static void removeWithForLoopDecrementOnRemove(List<Integer> list, int element) {
for (int i = 0; i < list.size(); i++) {
if (Objects.equals(element, list.get(i))) {
list.remove(i);
i--;
}
}
}
static void removeWithForLoopIncrementIfRemains(List<Integer> list, int element) {
for (int i = 0; i < list.size();) {
if (Objects.equals(element, list.get(i))) {
list.remove(i);
} else {
i++;
}
}
}
static void removeWithForEachLoop(List<Integer> list, int element) {
for (Integer number : list) {
if (Objects.equals(number, element)) {
list.remove(number);
}
}
}
static void removeWithIterator(List<Integer> list, int element) {
for (Iterator<Integer> i = list.iterator(); i.hasNext();) {
Integer number = i.next();
if (Objects.equals(number, element)) {
i.remove();
}
}
}
static List<Integer> removeWithCollectingAndReturningRemainingElements(List<Integer> list, int element) {
List<Integer> remainingElements = new ArrayList<>();
for (Integer number : list) {
if (!Objects.equals(number, element)) {
remainingElements.add(number);
}
}
return remainingElements;
}
static void removeWithCollectingRemainingElementsAndAddingToOriginalList(List<Integer> list, int element) {
List<Integer> remainingElements = new ArrayList<>();
for (Integer number : list) {
if (!Objects.equals(number, element)) {
remainingElements.add(number);
}
}
list.clear();
list.addAll(remainingElements);
}
static List<Integer> removeWithStreamFilter(List<Integer> list, Integer element) {
return list.stream()
.filter(e -> !Objects.equals(e, element))
.collect(Collectors.toList());
}
static void removeWithRemoveIf(List<Integer> list, Integer element) {
list.removeIf(n -> Objects.equals(n, element));
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull {
/**
* This method shows how to make a null safe stream from a collection through the use of
* emptyIfNull() method from Apache Commons CollectionUtils library
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return emptyIfNull(collection).stream();
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingJava8OptionalContainer {
/**
* This method shows how to make a null safe stream from a collection through the use of
* Java SE 8s Optional Container
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return Optional.ofNullable(collection)
.map(Collection::stream)
.orElseGet(Stream::empty);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Collection;
import java.util.stream.Stream;
public class NullSafeCollectionStreamsUsingNullDereferenceCheck {
/**
* This method shows how to make a null safe stream from a collection through the use of a check
* to prevent null dereferences
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return collection == null ? Stream.empty() : collection.stream();
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.thread_safe_lifo;
import java.util.ArrayDeque;
/**
* Deque Based Stack implementation.
*/
public class DequeBasedSynchronizedStack<T> {
// Internal Deque which gets decorated for synchronization.
private ArrayDeque<T> dequeStore = new ArrayDeque<>();
public DequeBasedSynchronizedStack(int initialCapacity) {
this.dequeStore = new ArrayDeque<>(initialCapacity);
}
public DequeBasedSynchronizedStack() {
}
public synchronized T pop() {
return this.dequeStore.pop();
}
public synchronized void push(T element) {
this.dequeStore.push(element);
}
public synchronized T peek() {
return this.dequeStore.peek();
}
public synchronized int size() {
return this.dequeStore.size();
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,13 +1,14 @@
package com.baeldung.convertlisttomap;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
public class ConvertListToMapServiceUnitTest {
List<Animal> list;

View File

@ -1,15 +1,15 @@
package com.baeldung.convertlisttomap;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
public class ConvertListWithDiplicatedIdToMapServiceUnitTest {
List<Animal> duplicatedIdList;

View File

@ -0,0 +1,44 @@
package com.baeldung.java.filtering;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
public class CollectionFiltersUnitTest {
private static final Collection<Integer> BASE_INTEGER_COLLECTION = Arrays.asList(9, 14, 2, 7, 1, 5, 8);
private static final Collection<Integer> EXPECTED_EVEN_FILTERED_COLLECTION = Arrays.asList(14, 2, 8);
@Test
public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() {
final Collection<String> baseStrings = Arrays.asList("java", "baeldung", "type", "example", "other");
Collection<String> filtered = StreamsCollectionFilter.filterCollectionHelperMethod(baseStrings, item -> item.length() == 4);
assertThat(filtered).containsExactlyInAnyOrder("java", "type");
}
@Test
public void givenAnIntegerCollection_whenFilteringEvenValues_thenObtainTheFilteredCollectionForAllCases() {
Collection<Integer> filteredWithStreams1 = StreamsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
Collection<Integer> filteredWithCollectionUtils = CollectionUtilsCollectionFilter.findEvenNumbers(new ArrayList<>(BASE_INTEGER_COLLECTION));
Collection<Integer> filteredWithEclipseCollections = EclipseCollectionsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
Collection<Integer> filteredWithEclipseCollectionsUsingIterate = EclipseCollectionsCollectionFilter.findEvenNumbersUsingIterate(BASE_INTEGER_COLLECTION);
Collection<Integer> filteredWithGuava = GuavaCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
assertThat(filteredWithStreams1).hasSameElementsAs(filteredWithCollectionUtils)
.hasSameElementsAs(filteredWithEclipseCollections)
.hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate)
.hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate)
.hasSameElementsAs(filteredWithGuava)
.hasSameElementsAs(EXPECTED_EVEN_FILTERED_COLLECTION);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.java.map.initialize;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.junit.Test;
public class MapInitializerUnitTest {
@Test
public void givenStaticMap_whenUpdated_thenCorrect() {
MapInitializer.articleMapOne.put("NewArticle1", "Convert array to List");
assertEquals(MapInitializer.articleMapOne.get("NewArticle1"), "Convert array to List");
}
@Test(expected=UnsupportedOperationException.class)
public void givenSingleTonMap_whenEntriesAdded_throwsException() {
Map<String, String> map = MapInitializer.createSingletonMap();
map.put("username2", "password2");
}
}

View File

@ -0,0 +1,69 @@
package com.baeldung.list.listoflist;
import com.baeldung.java.list.Flower;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.*;
public class AddElementsToListUnitTest {
List<Flower> flowers;
@Before
public void init() {
this.flowers = new ArrayList<>(Arrays.asList(
new Flower("Poppy", 12),
new Flower("Anemone", 8),
new Flower("Catmint", 12)));
}
@Test
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() {
List<Flower> anotherList = new ArrayList<>();
anotherList.addAll(flowers);
assertEquals(anotherList.size(), flowers.size());
Assert.assertTrue(anotherList.containsAll(flowers));
}
@Test
public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() {
List<Flower> anotherList = new ArrayList<>();
anotherList.addAll(flowers);
Flower flower = anotherList.get(0);
flower.setPetals(flowers.get(0).getPetals() * 3);
assertEquals(anotherList.size(), flowers.size());
Assert.assertTrue(anotherList.containsAll(flowers));
}
@Test
public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() {
List<Flower> target = new ArrayList<>();
Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0));
assertEquals(target.size(), 4);
}
@Test
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() {
List<Flower> flowerVase = new ArrayList<>();
flowers.stream()
.skip(1)
.forEachOrdered(flowerVase::add);
assertEquals(flowerVase.size() + 1, flowers.size());
assertFalse(flowerVase.containsAll(flowers));
}
@Test
public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() {
List<Flower> flowerVase = new ArrayList<>();
flowers.stream()
.filter(f -> f.getPetals() > 10)
.forEachOrdered(flowerVase::add);
assertEquals(flowerVase.size() + 1, flowers.size());
assertFalse(flowerVase.containsAll(flowers));
}
@Test
public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() {
List<Flower> target = new ArrayList<>();
Optional.ofNullable(flowers)
.ifPresent(target::addAll);
assertNotNull(target);
assertEquals(target.size(), 3);
}
}

View File

@ -0,0 +1,210 @@
package com.baeldung.list.removeall;
import static com.baeldung.list.removeall.RemoveAll.removeWithCallingRemoveUntilModifies;
import static com.baeldung.list.removeall.RemoveAll.removeWithCollectingAndReturningRemainingElements;
import static com.baeldung.list.removeall.RemoveAll.removeWithCollectingRemainingElementsAndAddingToOriginalList;
import static com.baeldung.list.removeall.RemoveAll.removeWithForEachLoop;
import static com.baeldung.list.removeall.RemoveAll.removeWithForLoopDecrementOnRemove;
import static com.baeldung.list.removeall.RemoveAll.removeWithForLoopIncrementIfRemains;
import static com.baeldung.list.removeall.RemoveAll.removeWithIterator;
import static com.baeldung.list.removeall.RemoveAll.removeWithRemoveIf;
import static com.baeldung.list.removeall.RemoveAll.removeWithStandardForLoopUsingIndex;
import static com.baeldung.list.removeall.RemoveAll.removeWithStreamFilter;
import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopNonPrimitiveElement;
import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopPrimitiveElement;
import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopStoringFirstOccurrenceIndex;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.List;
import org.junit.Test;
public class RemoveAllUnitTest {
private List<Integer> list(Integer... elements) {
return new ArrayList<>(Arrays.asList(elements));
}
@Test
public void givenAList_whenRemovingElementsWithWhileLoopUsingPrimitiveElement_thenTheResultCorrect() {
// given
List<Integer> list = list(1, 2, 3);
int valueToRemove = 1;
// when
assertThatThrownBy(() -> removeWithWhileLoopPrimitiveElement(list, valueToRemove))
.isInstanceOf(IndexOutOfBoundsException.class);
}
@Test
public void givenAList_whenRemovingElementsWithWhileLoopUsingNonPrimitiveElement_thenTheResultCorrect() {
// given
List<Integer> list = list(1, 2, 3);
int valueToRemove = 1;
// when
removeWithWhileLoopNonPrimitiveElement(list, valueToRemove);
// then
assertThat(list).isEqualTo(list(2, 3));
}
@Test
public void givenAList_whenRemovingElementsWithWhileLoopStoringFirstOccurrenceIndex_thenTheResultCorrect() {
// given
List<Integer> list = list(1, 2, 3);
int valueToRemove = 1;
// when
removeWithWhileLoopStoringFirstOccurrenceIndex(list, valueToRemove);
// then
assertThat(list).isEqualTo(list(2, 3));
}
@Test
public void givenAList_whenRemovingElementsWithCallingRemoveUntilModifies_thenTheResultIsCorrect() {
// given
List<Integer> list = list(1, 1, 2, 3);
int valueToRemove = 1;
// when
removeWithCallingRemoveUntilModifies(list, valueToRemove);
// then
assertThat(list).isEqualTo(list(2, 3));
}
@Test
public void givenAListWithoutDuplication_whenRemovingElementsWithStandardForLoopUsingIndex_thenTheResultIsCorrect() {
// given
List<Integer> list = list(1, 2, 3);
int valueToRemove = 1;
// when
removeWithStandardForLoopUsingIndex(list, valueToRemove);
// then
assertThat(list).isEqualTo(list(2, 3));
}
@Test
public void givenAListWithAdjacentElements_whenRemovingElementsWithStandardForLoop_thenTheResultIsInCorrect() {
// given
List<Integer> list = list(1, 1, 2, 3);
int valueToRemove = 1;
// when
removeWithStandardForLoopUsingIndex(list, valueToRemove);
// then
assertThat(list).isEqualTo(list(1, 2, 3));
}
@Test
public void givenAListWithAdjacentElements_whenRemovingElementsWithForLoopAndDecrementOnRemove_thenTheResultIsCorrect() {
// given
List<Integer> list = list(1, 1, 2, 3);
int valueToRemove = 1;
// when
removeWithForLoopDecrementOnRemove(list, valueToRemove);
// then
assertThat(list).isEqualTo(list(2, 3));
}
@Test
public void givenAListWithAdjacentElements_whenRemovingElementsWithForLoopAndIncrementIfRemains_thenTheResultIsCorrect() {
// given
List<Integer> list = list(1, 1, 2, 3);
int valueToRemove = 1;
// when
removeWithForLoopIncrementIfRemains(list, valueToRemove);
// then
assertThat(list).isEqualTo(list(2, 3));
}
@Test
public void givenAList_whenRemovingElementsWithForEachLoop_thenExceptionIsThrown() {
// given
List<Integer> list = list(1, 1, 2, 3);
int valueToRemove = 1;
// when
assertThatThrownBy(() -> removeWithForEachLoop(list, valueToRemove))
.isInstanceOf(ConcurrentModificationException.class);
}
@Test
public void givenAList_whenRemovingElementsWithIterator_thenTheResultIsCorrect() {
// given
List<Integer> list = list(1, 1, 2, 3);
int valueToRemove = 1;
// when
removeWithIterator(list, valueToRemove);
// then
assertThat(list).isEqualTo(list(2, 3));
}
@Test
public void givenAList_whenRemovingElementsWithCollectingAndReturningRemainingElements_thenTheResultIsCorrect() {
// given
List<Integer> list = list(1, 1, 2, 3);
int valueToRemove = 1;
// when
List<Integer> result = removeWithCollectingAndReturningRemainingElements(list, valueToRemove);
// then
assertThat(result).isEqualTo(list(2, 3));
}
@Test
public void givenAList_whenRemovingElementsWithCollectingRemainingAndAddingToOriginalList_thenTheResultIsCorrect() {
// given
List<Integer> list = list(1, 1, 2, 3);
int valueToRemove = 1;
// when
removeWithCollectingRemainingElementsAndAddingToOriginalList(list, valueToRemove);
// then
assertThat(list).isEqualTo(list(2, 3));
}
@Test
public void givenAList_whenRemovingElementsWithStreamFilter_thenTheResultIsCorrect() {
// given
List<Integer> list = list(1, 1, 2, 3);
int valueToRemove = 1;
// when
List<Integer> result = removeWithStreamFilter(list, valueToRemove);
// then
assertThat(result).isEqualTo(list(2, 3));
}
@Test
public void givenAList_whenRemovingElementsWithCallingRemoveIf_thenTheResultIsCorrect() {
// given
List<Integer> list = list(1, 1, 2, 3);
int valueToRemove = 1;
// when
removeWithRemoveIf(list, valueToRemove);
// then
assertThat(list).isEqualTo(list(2, 3));
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.list.removefirst;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class RemoveFirstElementUnitTest {
private List<String> list = new ArrayList<>();
private LinkedList<String> linkedList = new LinkedList<>();
@Before
public void init() {
list.add("cat");
list.add("dog");
list.add("pig");
list.add("cow");
list.add("goat");
linkedList.add("cat");
linkedList.add("dog");
linkedList.add("pig");
linkedList.add("cow");
linkedList.add("goat");
}
@Test
public void givenList_whenRemoveFirst_thenRemoved() {
list.remove(0);
assertThat(list, hasSize(4));
assertThat(list, not(contains("cat")));
}
@Test
public void givenLinkedList_whenRemoveFirst_thenRemoved() {
linkedList.removeFirst();
assertThat(linkedList, hasSize(4));
assertThat(linkedList, not(contains("cat")));
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.*;
public class NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest {
private final NullSafeCollectionStreamsUsingCommonsEmptyIfNull instance =
new NullSafeCollectionStreamsUsingCommonsEmptyIfNull();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.*;
public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance =
new NullSafeCollectionStreamsUsingJava8OptionalContainer();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.nullsafecollectionstreams;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.*;
public class NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest {
private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance =
new NullSafeCollectionStreamsUsingNullDereferenceCheck();
@Test
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
Collection<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@ -0,0 +1,101 @@
package com.baeldung.stack_tests;
import com.baeldung.thread_safe_lifo.DequeBasedSynchronizedStack;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayDeque;
import java.util.concurrent.ConcurrentLinkedDeque;
import static java.util.stream.IntStream.range;
/**
* Correctness tests for Stack in multi threaded environment.
*/
public class MultithreadingCorrectnessStackUnitTest {
@Test
public void givenSynchronizedDeque_whenExecutedParallel_thenWorkRight() {
DequeBasedSynchronizedStack<Integer> deque = new DequeBasedSynchronizedStack<>();
// Serial execution of push on ConcurrentLinkedQueue will always result in correct execution.
range(1, 10000).forEach(value -> deque.push(value));
int sum = 0;
while(deque.peek() != null) {
sum += deque.pop();
}
Assert.assertEquals(49995000, sum);
// Parallel execution of push on ConcurrentLinkedQueue will always result in correct execution.
range(1, 10000).parallel().forEach(value -> deque.push(value));
sum = 0;
while(deque.peek() != null) {
sum += deque.pop();
}
Assert.assertEquals(49995000, sum);
}
@Test
public void givenConcurrentLinkedQueue_whenExecutedParallel_thenWorkRight() {
ConcurrentLinkedDeque<Integer> deque = new ConcurrentLinkedDeque<>();
// Serial execution of push on ConcurrentLinkedQueue will always result in correct execution.
range(1, 10000).forEach(value -> deque.push(value));
int sum = 0;
while(deque.peek() != null) {
sum += deque.pop();
}
Assert.assertEquals(49995000, sum);
// Parallel execution of push on ConcurrentLinkedQueue will always result in correct execution.
range(1, 10000).parallel().forEach(value -> deque.push(value));
sum = 0;
while(deque.peek() != null) {
sum += deque.pop();
}
Assert.assertEquals(49995000, sum);
}
@Test
public void givenArrayDeque_whenExecutedParallel_thenShouldFail() {
ArrayDeque<Integer> deque = new ArrayDeque<>();
// Serial execution of push on ArrayDeque will always result in correct execution.
range(1, 10000).forEach(value -> deque.push(value));
int sum = 0;
while(deque.peek() != null) {
sum += deque.pop();
}
Assert.assertEquals(49995000, sum);
// Parallel execution of push on ArrayDeque will not result in correct execution.
range(1, 10000).parallel().forEach(value -> deque.push(value));
sum = 0;
while(deque.peek() != null) {
sum += deque.pop();
}
// This shouldn't happen.
if(sum == 49995000) {
System.out.println("Something wrong in the environment, Please try some big value and check");
// To safe-guard build without test failures.
return;
}
Assert.assertNotEquals(49995000, sum);
}
}

View File

@ -0,0 +1,63 @@
package com.baeldung.stack_tests;
import com.baeldung.thread_safe_lifo.DequeBasedSynchronizedStack;
import com.google.common.collect.Streams;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.Stack;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.stream.Stream;
import static java.util.stream.IntStream.range;
/**
* These tests are to understand the Stack implementation in Java Collections.
*/
public class StackUnitTest {
@Test
public void givenStack_whenPushPopPeek_thenWorkRight() {
Stack<String> namesStack = new Stack<>();
namesStack.push("Bill Gates");
namesStack.push("Elon Musk");
Assert.assertEquals("Elon Musk", namesStack.peek());
Assert.assertEquals("Elon Musk", namesStack.pop());
Assert.assertEquals("Bill Gates", namesStack.pop());
Assert.assertEquals(0, namesStack.size());
}
@Test
public void givenSynchronizedDeque_whenPushPopPeek_thenWorkRight() {
DequeBasedSynchronizedStack<String> namesStack = new DequeBasedSynchronizedStack<>();
namesStack.push("Bill Gates");
namesStack.push("Elon Musk");
Assert.assertEquals("Elon Musk", namesStack.peek());
Assert.assertEquals("Elon Musk", namesStack.pop());
Assert.assertEquals("Bill Gates", namesStack.pop());
Assert.assertEquals(0, namesStack.size());
}
@Test
public void givenConcurrentLinkedDeque_whenPushPopPeek_thenWorkRight() {
ConcurrentLinkedDeque<String> namesStack = new ConcurrentLinkedDeque<>();
namesStack.push("Bill Gates");
namesStack.push("Elon Musk");
Assert.assertEquals("Elon Musk", namesStack.peek());
Assert.assertEquals("Elon Musk", namesStack.pop());
Assert.assertEquals("Bill Gates", namesStack.pop());
Assert.assertEquals(0, namesStack.size());
}
}

View File

@ -38,3 +38,4 @@
- [Priority-based Job Scheduling in Java](http://www.baeldung.com/java-priority-job-schedule)
- [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer)
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)

View File

@ -28,3 +28,5 @@
- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)
- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)
- [Download a File From an URL in Java](http://www.baeldung.com/java-download-file)
- [Create a Symbolic Link with Java](http://www.baeldung.com/java-symlink)
- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter)

View File

@ -0,0 +1,48 @@
package com.baeldung.file;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class FilenameFilterManualTest {
private static File directory;
@BeforeClass
public static void setupClass() {
directory = new File(FilenameFilterManualTest.class.getClassLoader()
.getResource("testFolder")
.getFile());
}
@Test
public void whenFilteringFilesEndingWithJson_thenEqualExpectedFiles() {
FilenameFilter filter = (dir, name) -> name.endsWith(".json");
String[] expectedFiles = { "people.json", "students.json" };
String[] actualFiles = directory.list(filter);
Assert.assertArrayEquals(expectedFiles, actualFiles);
}
@Test
public void whenFilteringFilesEndingWithXml_thenEqualExpectedFiles() {
Predicate<String> predicate = (name) -> name.endsWith(".xml");
String[] expectedFiles = { "teachers.xml", "workers.xml" };
List<String> files = Arrays.stream(directory.list())
.filter(predicate)
.collect(Collectors.toList());
String[] actualFiles = files.toArray(new String[files.size()]);
Assert.assertArrayEquals(expectedFiles, actualFiles);
}
}

View File

@ -0,0 +1 @@
{}

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