commit
4bdec0a84d
|
@ -6,15 +6,69 @@
|
|||
<sourceOutputDir name="target/generated-sources/annotations" />
|
||||
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
|
||||
<outputRelativeToContentRoot value="true" />
|
||||
<module name="jmh" />
|
||||
<module name="assertion-libraries" />
|
||||
<module name="cucumber" />
|
||||
<module name="core-java-annotations" />
|
||||
<module name="jackson-simple" />
|
||||
<module name="spring-testing-2" />
|
||||
<module name="test-containers" />
|
||||
<module name="mockserver" />
|
||||
<module name="spring-testing" />
|
||||
<module name="xml" />
|
||||
<module name="core-java-datetime-conversion" />
|
||||
<module name="testing-libraries" />
|
||||
<module name="mocks" />
|
||||
<module name="load-testing-comparison" />
|
||||
<module name="junit-5-basics" />
|
||||
<module name="mockito-2" />
|
||||
<module name="testing-assertions" />
|
||||
<module name="easymock" />
|
||||
<module name="core-java-collections-list" />
|
||||
<module name="junit5-migration" />
|
||||
<module name="core-java-io" />
|
||||
<module name="easy-random" />
|
||||
<module name="junit-5" />
|
||||
<module name="junit-4" />
|
||||
<module name="junit-5-advanced" />
|
||||
<module name="rest-testing" />
|
||||
<module name="jackson-exceptions" />
|
||||
<module name="core-java-8" />
|
||||
<module name="jackson-conversions" />
|
||||
<module name="math-test-functions" />
|
||||
<module name="java-numbers-2" />
|
||||
<module name="jackson-annotations" />
|
||||
<module name="java-numbers" />
|
||||
<module name="mockito" />
|
||||
<module name="jackson" />
|
||||
<module name="groovy-spock" />
|
||||
<module name="jackson-conversions-2" />
|
||||
<module name="codebank" />
|
||||
<module name="selenium-junit-testng" />
|
||||
<module name="junit5-annotations" />
|
||||
<module name="mockito-3" />
|
||||
<module name="powermock" />
|
||||
<module name="zerocode" />
|
||||
<module name="gatling" />
|
||||
<module name="discourse" />
|
||||
<module name="rest-assured" />
|
||||
<module name="jackson-custom-conversions" />
|
||||
<module name="testing-libraries-2" />
|
||||
<module name="string-test-functions" />
|
||||
<module name="xmlunit-2" />
|
||||
<module name="testng" />
|
||||
<module name="hamcrest" />
|
||||
</profile>
|
||||
</annotationProcessing>
|
||||
<bytecodeTargetLevel>
|
||||
<module name="codebank" target="11" />
|
||||
<module name="discourse" target="11" />
|
||||
<module name="parent-modules" target="11" />
|
||||
<module name="toolkits" target="1.5" />
|
||||
</bytecodeTargetLevel>
|
||||
</component>
|
||||
<component name="JavacSettings">
|
||||
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
|
||||
<module name="codebank" options="" />
|
||||
<module name="discourse" options="" />
|
||||
<module name="java-numbers" options="" />
|
||||
<module name="java-numbers-2" options="" />
|
||||
<module name="jmh" options="--add-exports java.base/jdk.internal.vm.annotation=ALL-UNNAMED" />
|
||||
<module name="xml" options="" />
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
|
@ -1,9 +1,64 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Encoding">
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-8/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-8/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-annotations/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-annotations/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-datetime-conversion/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-datetime-conversion/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-io/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-io/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/core-java-modules/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-annotations/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-annotations/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-conversions-2/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-conversions-2/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-conversions/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-conversions/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-custom-conversions/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-custom-conversions/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-exceptions/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-exceptions/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/jackson/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/jackson/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-modules/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-simple/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/jackson-simple/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/parent-java/java-numbers-2/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/parent-java/java-numbers-2/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/parent-java/java-numbers/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/parent-java/java-numbers/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/parent-java/jmh/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/parent-java/jmh/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/parent-java/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/parent-java/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/easy-random/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/easy-random/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/junit-5-basics/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/junit-5-basics/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/junit-5-basics/src/test/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/mockito-2/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/mockito-2/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/mockserver/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/mockserver/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/rest-testing/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/rest-testing/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/spring-testing/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/spring-testing/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/testing-modules/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/toolkits/codebank/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/toolkits/codebank/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/toolkits/discourse/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/toolkits/discourse/src/main/resources" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/xml/src/main/java" charset="UTF-8" />
|
||||
<file url="file://$PROJECT_DIR$/xml/src/main/resources" charset="UTF-8" />
|
||||
</component>
|
||||
</project>
|
|
@ -6,6 +6,11 @@
|
|||
<option name="name" value="Central Repository" />
|
||||
<option name="url" value="https://repo.maven.apache.org/maven2" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="m2-ossez-com-m2" />
|
||||
<option name="name" value="m2-ossez-com-m2" />
|
||||
<option name="url" value="https://m2-ossez-com-206755003006.d.codeartifact.us-east-2.amazonaws.com/maven/m2/" />
|
||||
</remote-repository>
|
||||
<remote-repository>
|
||||
<option name="id" value="central" />
|
||||
<option name="name" value="Maven Central repository" />
|
||||
|
|
|
@ -0,0 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="JpaBuddyIdeaProjectConfig">
|
||||
<option name="defaultUnitInitialized" value="true" />
|
||||
</component>
|
||||
</project>
|
|
@ -1,5 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="MavenProjectsManager">
|
||||
<option name="originalFiles">
|
||||
<list>
|
||||
|
|
|
@ -1,11 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/toolkits/codebank/codebank.iml" filepath="$PROJECT_DIR$/toolkits/codebank/codebank.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/toolkits/discourse/discourse.iml" filepath="$PROJECT_DIR$/toolkits/discourse/discourse.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/parent-modules.iml" filepath="$PROJECT_DIR$/parent-modules.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/toolkits/toolkits.iml" filepath="$PROJECT_DIR$/toolkits/toolkits.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
|
@ -4,63 +4,384 @@
|
|||
<option name="autoReloadType" value="SELECTIVE" />
|
||||
</component>
|
||||
<component name="ChangeListManager">
|
||||
<list default="true" id="e4ccec40-1722-49be-ba56-1cba428e2e66" name="Default Changelist" comment="Change code for full project compile">
|
||||
<list default="true" id="2a855b03-5ee0-4324-b916-110994784a14" name="Changes" comment="针对 Java List 相关的一些操作进行说明和示例">
|
||||
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/pom.xml" beforeDir="false" afterPath="$PROJECT_DIR$/pom.xml" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/findanelement/Customer.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/ossez/findanelement/Customer.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/ossez/findanelement/FindACustomerInGivenList.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java/list/CustomList.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/ossez/java/list/CustomList.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java/list/ReverseIterator.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/ossez/java/list/ReverseIterator.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java_8_features/Car.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/ossez/java_8_features/Car.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/java_8_features/Person.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/ossez/java_8_features/Person.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/Flower.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/ossez/list/Flower.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Pen.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/ossez/list/listoflist/Pen.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Pencil.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/ossez/list/listoflist/Pencil.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Rubber.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/ossez/list/listoflist/Rubber.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/listoflist/Stationery.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/ossez/list/listoflist/Stationery.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/baeldung/list/removeall/RemoveAll.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/main/java/com/ossez/list/removeall/RemoveAll.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/collections/JavaCollectionCleanupUnitTest.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/ossez/collections/JavaCollectionCleanupUnitTest.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/ossez/findanelement/FindACustomerInGivenListUnitTest.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java/list/CustomListUnitTest.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/ossez/java/list/CustomListUnitTest.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java/list/ReverseIteratorUnitTest.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/ossez/java/list/ReverseIteratorUnitTest.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/ossez/java8/Java8CollectionCleanupUnitTest.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/ossez/java8/Java8MaxMinUnitTest.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/AddElementsUnitTest.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/ossez/list/AddElementsUnitTest.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/listoflist/ListOfListsUnitTest.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/ossez/list/listoflist/ListOfListsUnitTest.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/random/RandomListElementUnitTest.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/ossez/list/random/RandomListElementUnitTest.java" afterDir="false" />
|
||||
<change beforePath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java" beforeDir="false" afterPath="$PROJECT_DIR$/core-java-modules/core-java-collections-list/src/test/java/com/ossez/list/removeall/RemoveAllUnitTest.java" afterDir="false" />
|
||||
</list>
|
||||
<option name="SHOW_DIALOG" value="false" />
|
||||
<option name="HIGHLIGHT_CONFLICTS" value="true" />
|
||||
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
|
||||
<option name="LAST_RESOLUTION" value="IGNORE" />
|
||||
</component>
|
||||
<component name="ComposerSettings">
|
||||
<execution />
|
||||
</component>
|
||||
<component name="Git.Settings">
|
||||
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
|
||||
</component>
|
||||
<component name="ProjectId" id="1rgubunw7ryTECA0xroZNQRefbN" />
|
||||
<component name="GitSEFilterConfiguration">
|
||||
<file-type-list>
|
||||
<filtered-out-file-type name="LOCAL_BRANCH" />
|
||||
<filtered-out-file-type name="REMOTE_BRANCH" />
|
||||
<filtered-out-file-type name="TAG" />
|
||||
<filtered-out-file-type name="COMMIT_BY_MESSAGE" />
|
||||
</file-type-list>
|
||||
</component>
|
||||
<component name="JpbToolWindowState">
|
||||
<option name="myId2FirstActivated">
|
||||
<map>
|
||||
<entry key="JPA Structure" value="true" />
|
||||
<entry key="com.haulmont.jpb.jpaPalette" value="true" />
|
||||
<entry key="com.haulmont.jpb.jpaStructure" value="true" />
|
||||
</map>
|
||||
</option>
|
||||
<option name="myId2Visible">
|
||||
<map>
|
||||
<entry key="JPA Structure" value="false" />
|
||||
<entry key="com.haulmont.jpb.jpaPalette" value="false" />
|
||||
<entry key="com.haulmont.jpb.jpaStructure" value="false" />
|
||||
</map>
|
||||
</option>
|
||||
</component>
|
||||
<component name="MarkdownSettingsMigration">
|
||||
<option name="stateVersion" value="1" />
|
||||
</component>
|
||||
<component name="MavenRunner">
|
||||
<option name="skipTests" value="true" />
|
||||
</component>
|
||||
<component name="ProjectId" id="1yXq0B5lme8eyBDkbRBUHlwFMj2" />
|
||||
<component name="ProjectViewState">
|
||||
<option name="hideEmptyMiddlePackages" value="true" />
|
||||
<option name="showLibraryContents" value="true" />
|
||||
</component>
|
||||
<component name="PropertiesComponent">
|
||||
<property name="DatabaseDriversLRU" value="mariadb" />
|
||||
<property name="RunOnceActivity.OpenProjectViewOnStart" value="true" />
|
||||
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
|
||||
<property name="SHARE_PROJECT_CONFIGURATION_FILES" value="true" />
|
||||
<property name="TF_FMT" value="false" />
|
||||
<property name="WebServerToolWindowFactoryState" value="false" />
|
||||
<property name="aspect.path.notification.shown" value="true" />
|
||||
<property name="last_opened_file_path" value="$PROJECT_DIR$/src/test/java/com/ossez/codebank/algorithm/tests" />
|
||||
<property name="node.js.detected.package.eslint" value="true" />
|
||||
<property name="node.js.detected.package.tslint" value="true" />
|
||||
<property name="node.js.selected.package.eslint" value="(autodetect)" />
|
||||
<property name="node.js.selected.package.tslint" value="(autodetect)" />
|
||||
<property name="nodejs_package_manager_path" value="npm" />
|
||||
<property name="project.structure.last.edited" value="Modules" />
|
||||
<property name="project.structure.proportion" value="0.0" />
|
||||
<property name="project.structure.side.proportion" value="0.0" />
|
||||
<property name="project.structure.proportion" value="0.13908207" />
|
||||
<property name="project.structure.side.proportion" value="0.24043715" />
|
||||
<property name="settings.editor.selected.configurable" value="MavenSettings" />
|
||||
</component>
|
||||
<component name="RunManager">
|
||||
<configuration default="true" type="ArquillianJUnit" factoryName="" nameIsGenerated="true">
|
||||
<option name="arquillianRunConfiguration">
|
||||
<value>
|
||||
<option name="containerStateName" value="" />
|
||||
</value>
|
||||
</option>
|
||||
<component name="RecentsManager">
|
||||
<key name="CopyFile.RECENT_KEYS">
|
||||
<recent name="D:\WorkDir\Repository\GitHub\cwiki-us-docs\java-tutorials\src\test\java\com\ossez\codebank\algorithm\tests" />
|
||||
<recent name="D:\WorkDir\Repository\GitHub\cwiki-us-docs\java-tutorials\parent-java" />
|
||||
<recent name="D:\WorkDir\Repository\GitHub\cwiki-us-docs\java-tutorials\xml\src\test\resources" />
|
||||
<recent name="D:\WorkDir\Repository\GitHub\cwiki-us-docs\java-tutorials" />
|
||||
</key>
|
||||
<key name="CopyClassDialog.RECENTS_KEY">
|
||||
<recent name="com.baeldung.list" />
|
||||
</key>
|
||||
</component>
|
||||
<component name="RunManager" selected="JUnit.AddElementsUnitTest.givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems">
|
||||
<configuration name="AddElementsUnitTest.givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems" type="JUnit" factoryName="JUnit" temporary="true" nameIsGenerated="true">
|
||||
<module name="core-java-collections-list" />
|
||||
<extension name="coverage">
|
||||
<pattern>
|
||||
<option name="PATTERN" value="com.baeldung.list.*" />
|
||||
<option name="ENABLED" value="true" />
|
||||
</pattern>
|
||||
</extension>
|
||||
<option name="PACKAGE_NAME" value="com.baeldung.list" />
|
||||
<option name="MAIN_CLASS_NAME" value="com.baeldung.list.AddElementsUnitTest" />
|
||||
<option name="METHOD_NAME" value="givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems" />
|
||||
<option name="TEST_OBJECT" value="method" />
|
||||
<method v="2">
|
||||
<option name="Make" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
<configuration name="CustomListUnitTest.givenEmptyList_whenIsEmpty_thenTrueIsReturned" type="JUnit" factoryName="JUnit" temporary="true" nameIsGenerated="true">
|
||||
<module name="core-java-collections-list" />
|
||||
<extension name="coverage">
|
||||
<pattern>
|
||||
<option name="PATTERN" value="com.baeldung.java.list.*" />
|
||||
<option name="ENABLED" value="true" />
|
||||
</pattern>
|
||||
</extension>
|
||||
<option name="PACKAGE_NAME" value="com.baeldung.java.list" />
|
||||
<option name="MAIN_CLASS_NAME" value="com.baeldung.java.list.CustomListUnitTest" />
|
||||
<option name="METHOD_NAME" value="givenEmptyList_whenIsEmpty_thenTrueIsReturned" />
|
||||
<option name="TEST_OBJECT" value="method" />
|
||||
<method v="2">
|
||||
<option name="Make" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
<configuration name="JavaCollectionCleanupUnitTest" type="JUnit" factoryName="JUnit" temporary="true" nameIsGenerated="true">
|
||||
<module name="core-java-collections-list" />
|
||||
<extension name="coverage">
|
||||
<pattern>
|
||||
<option name="PATTERN" value="com.baeldung.collections.*" />
|
||||
<option name="ENABLED" value="true" />
|
||||
</pattern>
|
||||
</extension>
|
||||
<option name="PACKAGE_NAME" value="com.baeldung.collections" />
|
||||
<option name="MAIN_CLASS_NAME" value="com.baeldung.collections.JavaCollectionCleanupUnitTest" />
|
||||
<option name="TEST_OBJECT" value="class" />
|
||||
<method v="2">
|
||||
<option name="Make" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
<configuration name="RandomListElementUnitTest.givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom" type="JUnit" factoryName="JUnit" temporary="true" nameIsGenerated="true">
|
||||
<module name="core-java-collections-list" />
|
||||
<extension name="coverage">
|
||||
<pattern>
|
||||
<option name="PATTERN" value="com.baeldung.list.random.*" />
|
||||
<option name="ENABLED" value="true" />
|
||||
</pattern>
|
||||
</extension>
|
||||
<option name="PACKAGE_NAME" value="com.baeldung.list.random" />
|
||||
<option name="MAIN_CLASS_NAME" value="com.baeldung.list.random.RandomListElementUnitTest" />
|
||||
<option name="METHOD_NAME" value="givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom" />
|
||||
<option name="TEST_OBJECT" value="method" />
|
||||
<method v="2">
|
||||
<option name="Make" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
<configuration name="RemoveAllUnitTest.givenAList_whenRemovingElementsWithWhileLoopUsingPrimitiveElement_thenTheResultCorrect" type="JUnit" factoryName="JUnit" temporary="true" nameIsGenerated="true">
|
||||
<module name="core-java-collections-list" />
|
||||
<extension name="coverage">
|
||||
<pattern>
|
||||
<option name="PATTERN" value="com.baeldung.list.removeall.*" />
|
||||
<option name="ENABLED" value="true" />
|
||||
</pattern>
|
||||
</extension>
|
||||
<option name="PACKAGE_NAME" value="com.baeldung.list.removeall" />
|
||||
<option name="MAIN_CLASS_NAME" value="com.baeldung.list.removeall.RemoveAllUnitTest" />
|
||||
<option name="METHOD_NAME" value="givenAList_whenRemovingElementsWithWhileLoopUsingPrimitiveElement_thenTheResultCorrect" />
|
||||
<option name="TEST_OBJECT" value="method" />
|
||||
<method v="2">
|
||||
<option name="Make" enabled="true" />
|
||||
</method>
|
||||
</configuration>
|
||||
<list>
|
||||
<item itemvalue="JUnit.RandomListElementUnitTest.givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom" />
|
||||
<item itemvalue="JUnit.CustomListUnitTest.givenEmptyList_whenIsEmpty_thenTrueIsReturned" />
|
||||
<item itemvalue="JUnit.JavaCollectionCleanupUnitTest" />
|
||||
<item itemvalue="JUnit.RemoveAllUnitTest.givenAList_whenRemovingElementsWithWhileLoopUsingPrimitiveElement_thenTheResultCorrect" />
|
||||
<item itemvalue="JUnit.AddElementsUnitTest.givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems" />
|
||||
</list>
|
||||
<recent_temporary>
|
||||
<list>
|
||||
<item itemvalue="JUnit.AddElementsUnitTest.givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems" />
|
||||
<item itemvalue="JUnit.RemoveAllUnitTest.givenAList_whenRemovingElementsWithWhileLoopUsingPrimitiveElement_thenTheResultCorrect" />
|
||||
<item itemvalue="JUnit.JavaCollectionCleanupUnitTest" />
|
||||
<item itemvalue="JUnit.CustomListUnitTest.givenEmptyList_whenIsEmpty_thenTrueIsReturned" />
|
||||
<item itemvalue="JUnit.RandomListElementUnitTest.givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom" />
|
||||
</list>
|
||||
</recent_temporary>
|
||||
</component>
|
||||
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
|
||||
<component name="TaskManager">
|
||||
<task active="true" id="Default" summary="Default task">
|
||||
<changelist id="e4ccec40-1722-49be-ba56-1cba428e2e66" name="Default Changelist" comment="" />
|
||||
<created>1619410137650</created>
|
||||
<changelist id="2a855b03-5ee0-4324-b916-110994784a14" name="Changes" comment="" />
|
||||
<created>1632408056518</created>
|
||||
<option name="number" value="Default" />
|
||||
<option name="presentableId" value="Default" />
|
||||
<updated>1619410137650</updated>
|
||||
<workItem from="1619410141685" duration="410000" />
|
||||
<updated>1632408056518</updated>
|
||||
<workItem from="1632408057926" duration="1144000" />
|
||||
<workItem from="1632417263821" duration="6344000" />
|
||||
<workItem from="1632505123573" duration="254000" />
|
||||
<workItem from="1632767316507" duration="2832000" />
|
||||
<workItem from="1632843147814" duration="70000" />
|
||||
<workItem from="1632921802745" duration="10467000" />
|
||||
<workItem from="1633367518405" duration="9878000" />
|
||||
<workItem from="1633618804068" duration="450000" />
|
||||
<workItem from="1633632654458" duration="752000" />
|
||||
<workItem from="1635345165318" duration="10334000" />
|
||||
<workItem from="1635444765485" duration="1914000" />
|
||||
<workItem from="1636036083756" duration="1939000" />
|
||||
<workItem from="1637604679020" duration="4122000" />
|
||||
<workItem from="1643144156003" duration="50000" />
|
||||
<workItem from="1646495852750" duration="4995000" />
|
||||
<workItem from="1646839802700" duration="395000" />
|
||||
<workItem from="1647437503983" duration="720000" />
|
||||
<workItem from="1648647071224" duration="51293000" />
|
||||
<workItem from="1649427299582" duration="1874000" />
|
||||
<workItem from="1649700348383" duration="1281000" />
|
||||
<workItem from="1649775528408" duration="2679000" />
|
||||
<workItem from="1649855691174" duration="61000" />
|
||||
<workItem from="1649855771582" duration="613000" />
|
||||
<workItem from="1650042038314" duration="5798000" />
|
||||
</task>
|
||||
<task id="LOCAL-00001" summary="Change code for full project compile">
|
||||
<created>1619410303516</created>
|
||||
<task id="LOCAL-00001" summary="修改项目到不同的路径">
|
||||
<created>1632420206392</created>
|
||||
<option name="number" value="00001" />
|
||||
<option name="presentableId" value="LOCAL-00001" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1619410303516</updated>
|
||||
<updated>1632420206392</updated>
|
||||
</task>
|
||||
<option name="localTasksCounter" value="2" />
|
||||
<task id="LOCAL-00002" summary="Update change to different folder and set to rebuild">
|
||||
<created>1632420268850</created>
|
||||
<option name="number" value="00002" />
|
||||
<option name="presentableId" value="LOCAL-00002" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1632420268850</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00003" summary="Java number related and examples">
|
||||
<created>1632423632011</created>
|
||||
<option name="number" value="00003" />
|
||||
<option name="presentableId" value="LOCAL-00003" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1632423632011</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00004" summary="Init commit all code">
|
||||
<created>1632423824690</created>
|
||||
<option name="number" value="00004" />
|
||||
<option name="presentableId" value="LOCAL-00004" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1632423824690</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00005" summary="Init commit all code">
|
||||
<created>1632423847987</created>
|
||||
<option name="number" value="00005" />
|
||||
<option name="presentableId" value="LOCAL-00005" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1632423847987</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00006" summary="Check Prime numbers">
|
||||
<created>1632426542726</created>
|
||||
<option name="number" value="00006" />
|
||||
<option name="presentableId" value="LOCAL-00006" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1632426542726</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00007" summary="Add docs for xml process">
|
||||
<created>1632937568332</created>
|
||||
<option name="number" value="00007" />
|
||||
<option name="presentableId" value="LOCAL-00007" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1632937568332</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00008" summary="Add docs for xml process">
|
||||
<created>1632937611560</created>
|
||||
<option name="number" value="00008" />
|
||||
<option name="presentableId" value="LOCAL-00008" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1632937611560</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00009" summary="更新 JMH 的文档和代码">
|
||||
<created>1633373116785</created>
|
||||
<option name="number" value="00009" />
|
||||
<option name="presentableId" value="LOCAL-00009" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1633373116785</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00010" summary="Add JMH document and source code">
|
||||
<created>1633373171820</created>
|
||||
<option name="number" value="00010" />
|
||||
<option name="presentableId" value="LOCAL-00010" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1633373171820</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00011" summary="Add compiler for JMH https://www.ossez.com/t/intellij-idea/13759">
|
||||
<created>1633461594898</created>
|
||||
<option name="number" value="00011" />
|
||||
<option name="presentableId" value="LOCAL-00011" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1633461594898</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00012" summary="Update link for Java Microbenchmark Harness">
|
||||
<created>1633632799545</created>
|
||||
<option name="number" value="00012" />
|
||||
<option name="presentableId" value="LOCAL-00012" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1633632799545</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00013" summary="Main test function">
|
||||
<created>1636038085011</created>
|
||||
<option name="number" value="00013" />
|
||||
<option name="presentableId" value="LOCAL-00013" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1636038085011</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00014" summary="Add Junit5 test base">
|
||||
<created>1637605886622</created>
|
||||
<option name="number" value="00014" />
|
||||
<option name="presentableId" value="LOCAL-00014" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1637605886622</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00015" summary="Rename package to ossez">
|
||||
<created>1637606120688</created>
|
||||
<option name="number" value="00015" />
|
||||
<option name="presentableId" value="LOCAL-00015" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1637606120688</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00016" summary="Update the link for Junit 4 and @Before">
|
||||
<created>1637610032904</created>
|
||||
<option name="number" value="00016" />
|
||||
<option name="presentableId" value="LOCAL-00016" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1637610032904</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00017" summary="Copy source code for testing and update testing object">
|
||||
<created>1646496865741</created>
|
||||
<option name="number" value="00017" />
|
||||
<option name="presentableId" value="LOCAL-00017" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1646496865741</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00018" summary="Add logic for JSON to OBJ">
|
||||
<created>1646496916425</created>
|
||||
<option name="number" value="00018" />
|
||||
<option name="presentableId" value="LOCAL-00018" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1646496916425</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00019" summary="Format Jackson related source code and so on">
|
||||
<created>1649776367988</created>
|
||||
<option name="number" value="00019" />
|
||||
<option name="presentableId" value="LOCAL-00019" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1649776367988</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00020" summary="修改项目的编译">
|
||||
<created>1650048905070</created>
|
||||
<option name="number" value="00020" />
|
||||
<option name="presentableId" value="LOCAL-00020" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1650048905070</updated>
|
||||
</task>
|
||||
<task id="LOCAL-00021" summary="针对 Java List 相关的一些操作进行说明和示例">
|
||||
<created>1650048942808</created>
|
||||
<option name="number" value="00021" />
|
||||
<option name="presentableId" value="LOCAL-00021" />
|
||||
<option name="project" value="LOCAL" />
|
||||
<updated>1650048942808</updated>
|
||||
</task>
|
||||
<option name="localTasksCounter" value="22" />
|
||||
<servers />
|
||||
</component>
|
||||
<component name="TypeScriptGeneratedFilesManager">
|
||||
|
@ -78,7 +399,36 @@
|
|||
</option>
|
||||
</component>
|
||||
<component name="VcsManagerConfiguration">
|
||||
<MESSAGE value="Change code for full project compile" />
|
||||
<option name="LAST_COMMIT_MESSAGE" value="Change code for full project compile" />
|
||||
<MESSAGE value="修改项目到不同的路径" />
|
||||
<MESSAGE value="Update change to different folder and set to rebuild" />
|
||||
<MESSAGE value="Java number related and examples" />
|
||||
<MESSAGE value="Init commit all code" />
|
||||
<MESSAGE value="Check Prime numbers" />
|
||||
<MESSAGE value="Add docs for xml process" />
|
||||
<MESSAGE value="更新 JMH 的文档和代码" />
|
||||
<MESSAGE value="Add JMH document and source code" />
|
||||
<MESSAGE value="Add compiler for JMH https://www.ossez.com/t/intellij-idea/13759" />
|
||||
<MESSAGE value="Update link for Java Microbenchmark Harness" />
|
||||
<MESSAGE value="Main test function" />
|
||||
<MESSAGE value="Add Junit5 test base" />
|
||||
<MESSAGE value="Rename package to ossez" />
|
||||
<MESSAGE value="Update the link for Junit 4 and @Before" />
|
||||
<MESSAGE value="Copy source code for testing and update testing object" />
|
||||
<MESSAGE value="Add logic for JSON to OBJ" />
|
||||
<MESSAGE value="Format Jackson related source code and so on" />
|
||||
<MESSAGE value="修改项目的编译" />
|
||||
<MESSAGE value="针对 Java List 相关的一些操作进行说明和示例" />
|
||||
<option name="LAST_COMMIT_MESSAGE" value="针对 Java List 相关的一些操作进行说明和示例" />
|
||||
</component>
|
||||
<component name="XDebuggerManager">
|
||||
<breakpoint-manager>
|
||||
<breakpoints>
|
||||
<line-breakpoint enabled="true" type="java-line">
|
||||
<url>jar://C:/Program Files/RedHat/java-11-openjdk-11.0.11-1/lib/src.zip!/java.base/java/lang/Integer.java</url>
|
||||
<line>1056</line>
|
||||
<option name="timeStamp" value="1" />
|
||||
</line-breakpoint>
|
||||
</breakpoints>
|
||||
</breakpoint-manager>
|
||||
</component>
|
||||
</project>
|
|
@ -0,0 +1,26 @@
|
|||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
|
@ -0,0 +1,15 @@
|
|||
## Core Java 8
|
||||
|
||||
This module contains articles about Java 8 core features
|
||||
|
||||
### Relevant Articles:
|
||||
- [New Features in Java 8](https://www.baeldung.com/java-8-new-features)
|
||||
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
|
||||
- [Strategy Design Pattern in Java 8](https://www.baeldung.com/java-strategy-pattern)
|
||||
- [Guide to Java 8 Comparator.comparing()](https://www.baeldung.com/java-8-comparator-comparing)
|
||||
- [Guide to the Java 8 forEach](https://www.baeldung.com/foreach-java)
|
||||
- [Introduction to Spliterator in Java](https://www.baeldung.com/java-spliterator)
|
||||
- [Finding Min/Max in an Array with Java](https://www.baeldung.com/java-array-min-max)
|
||||
- [Internationalization and Localization in Java 8](https://www.baeldung.com/java-8-localization)
|
||||
- [Generalized Target-Type Inference in Java](https://www.baeldung.com/java-generalized-target-type-inference)
|
||||
- [[More -->]](/core-java-modules/core-java-8-2)
|
|
@ -0,0 +1,55 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-8</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-8</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.ossez.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.2-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-8</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.ossez.java_8_features;
|
||||
|
||||
public class Address {
|
||||
|
||||
private String street;
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package com.ossez.java_8_features;
|
||||
|
||||
public class CustomException extends RuntimeException {
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.ossez.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class OptionalAddress {
|
||||
|
||||
private String street;
|
||||
|
||||
public Optional<String> getStreet() {
|
||||
return Optional.ofNullable(street);
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.ossez.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class OptionalUser {
|
||||
|
||||
private OptionalAddress address;
|
||||
|
||||
public Optional<OptionalAddress> getAddress() {
|
||||
return Optional.of(address);
|
||||
}
|
||||
|
||||
public void setAddress(OptionalAddress address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.ossez.java_8_features;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class User {
|
||||
|
||||
private String name;
|
||||
|
||||
private Address address;
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public static boolean isRealUser(User user) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public String getOrThrow() {
|
||||
String value = null;
|
||||
Optional<String> valueOpt = Optional.ofNullable(value);
|
||||
String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
|
||||
return result;
|
||||
}
|
||||
|
||||
public boolean isLegalName(String name) {
|
||||
return name.length() > 3 && name.length() < 16;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.ossez.java_8_features;
|
||||
|
||||
public interface Vehicle {
|
||||
|
||||
void moveTo(long altitude, long longitude);
|
||||
|
||||
static String producer() {
|
||||
return "N&F Vehicles";
|
||||
}
|
||||
|
||||
default long[] startPosition() {
|
||||
return new long[] { 23, 15 };
|
||||
}
|
||||
|
||||
default String getOverview() {
|
||||
return "ATV made by " + producer();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
package com.ossez.java_8_features;
|
||||
|
||||
public class VehicleImpl implements Vehicle {
|
||||
|
||||
@Override
|
||||
public void moveTo(long altitude, long longitude) {
|
||||
// do nothing
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.ossez.java_8_features.groupingby;
|
||||
|
||||
public class BlogPost {
|
||||
private String title;
|
||||
private String author;
|
||||
private BlogPostType type;
|
||||
private int likes;
|
||||
|
||||
public BlogPost(String title, String author, BlogPostType type, int likes) {
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.type = type;
|
||||
this.likes = likes;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public BlogPostType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public int getLikes() {
|
||||
return likes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "BlogPost{" + "title='" + title + '\'' + ", type=" + type + ", likes=" + likes + '}';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.ossez.java_8_features.groupingby;
|
||||
|
||||
public enum BlogPostType {
|
||||
NEWS, REVIEW, GUIDE
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.ossez.java_8_features.groupingby;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class Tuple {
|
||||
private final BlogPostType type;
|
||||
private final String author;
|
||||
|
||||
public Tuple(BlogPostType type, String author) {
|
||||
this.type = type;
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public BlogPostType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null || getClass() != o.getClass())
|
||||
return false;
|
||||
Tuple tuple = (Tuple) o;
|
||||
return type == tuple.type && author.equals(tuple.author);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(type, author);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Tuple{" + "type=" + type + ", author='" + author + '\'' + '}';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.ossez.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();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.ossez.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 8’s 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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.ossez.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();
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.ossez.spliteratorAPI;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Article {
|
||||
private List<Author> listOfAuthors;
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public Article(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Article(List<Author> listOfAuthors, int id) {
|
||||
super();
|
||||
this.listOfAuthors = listOfAuthors;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public List<Author> getListOfAuthors() {
|
||||
return listOfAuthors;
|
||||
}
|
||||
|
||||
public void setListOfAuthors(List<Author> listOfAuthors) {
|
||||
this.listOfAuthors = listOfAuthors;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.ossez.spliteratorAPI;
|
||||
|
||||
public class Author {
|
||||
private String name;
|
||||
private int relatedArticleId;
|
||||
|
||||
public Author(String name, int relatedArticleId) {
|
||||
this.name = name;
|
||||
this.relatedArticleId = relatedArticleId;
|
||||
}
|
||||
|
||||
public int getRelatedArticleId() {
|
||||
return relatedArticleId;
|
||||
}
|
||||
|
||||
public void setRelatedArticleId(int relatedArticleId) {
|
||||
this.relatedArticleId = relatedArticleId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "[name: " + name + ", relatedId: " + relatedArticleId + "]";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package com.ossez.spliteratorAPI;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class Executor {
|
||||
|
||||
public static int countAutors(Stream<Author> stream) {
|
||||
RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true),
|
||||
RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine);
|
||||
return wordCounter.getCounter();
|
||||
}
|
||||
|
||||
public static List<Article> generateElements() {
|
||||
return Stream.generate(() -> new Article("Java")).limit(35000).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.ossez.spliteratorAPI;
|
||||
|
||||
public class RelatedAuthorCounter {
|
||||
private final int counter;
|
||||
private final boolean isRelated;
|
||||
|
||||
public RelatedAuthorCounter(int counter, boolean isRelated) {
|
||||
this.counter = counter;
|
||||
this.isRelated = isRelated;
|
||||
}
|
||||
|
||||
public RelatedAuthorCounter accumulate(Author author) {
|
||||
if (author.getRelatedArticleId() == 0) {
|
||||
return isRelated ? this : new RelatedAuthorCounter(counter, true);
|
||||
} else {
|
||||
return isRelated ? new RelatedAuthorCounter(counter + 1, false) : this;
|
||||
}
|
||||
}
|
||||
|
||||
public RelatedAuthorCounter combine(RelatedAuthorCounter RelatedAuthorCounter) {
|
||||
return new RelatedAuthorCounter(counter + RelatedAuthorCounter.counter, RelatedAuthorCounter.isRelated);
|
||||
}
|
||||
|
||||
public int getCounter() {
|
||||
return counter;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.ossez.spliteratorAPI;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Spliterator;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class RelatedAuthorSpliterator implements Spliterator<Author> {
|
||||
private final List<Author> list;
|
||||
AtomicInteger current = new AtomicInteger();
|
||||
|
||||
public RelatedAuthorSpliterator(List<Author> list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean tryAdvance(Consumer<? super Author> action) {
|
||||
|
||||
action.accept(list.get(current.getAndIncrement()));
|
||||
return current.get() < list.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Spliterator<Author> trySplit() {
|
||||
int currentSize = list.size() - current.get();
|
||||
if (currentSize < 10) {
|
||||
return null;
|
||||
}
|
||||
for (int splitPos = currentSize / 2 + current.intValue(); splitPos < list.size(); splitPos++) {
|
||||
if (list.get(splitPos).getRelatedArticleId() == 0) {
|
||||
Spliterator<Author> spliterator = new RelatedAuthorSpliterator(list.subList(current.get(), splitPos));
|
||||
current.set(splitPos);
|
||||
return spliterator;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long estimateSize() {
|
||||
return list.size() - current.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int characteristics() {
|
||||
return CONCURRENT;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.ossez.spliteratorAPI;
|
||||
|
||||
import java.util.Spliterator;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class Task implements Callable<String> {
|
||||
private Spliterator<Article> spliterator;
|
||||
private final static String SUFFIX = "- published by Baeldung";
|
||||
|
||||
public Task(Spliterator<Article> spliterator) {
|
||||
this.spliterator = spliterator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String call() {
|
||||
int current = 0;
|
||||
while (spliterator.tryAdvance(article -> {
|
||||
article.setName(article.getName()
|
||||
.concat(SUFFIX));
|
||||
})) {
|
||||
current++;
|
||||
}
|
||||
;
|
||||
return Thread.currentThread()
|
||||
.getName() + ":" + current;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.ossez.strategy;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class ChristmasDiscounter implements Discounter {
|
||||
|
||||
@Override
|
||||
public BigDecimal apply(BigDecimal amount) {
|
||||
return amount.multiply(BigDecimal.valueOf(0.9));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.ossez.strategy;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
public interface Discounter extends UnaryOperator<BigDecimal> {
|
||||
|
||||
default Discounter combine(Discounter after) {
|
||||
return value -> after.apply(this.apply(value));
|
||||
}
|
||||
|
||||
static Discounter christmas() {
|
||||
return (amount) -> amount.multiply(BigDecimal.valueOf(0.9));
|
||||
}
|
||||
|
||||
static Discounter newYear() {
|
||||
return (amount) -> amount.multiply(BigDecimal.valueOf(0.8));
|
||||
}
|
||||
|
||||
static Discounter easter() {
|
||||
return (amount) -> amount.multiply(BigDecimal.valueOf(0.5));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.ossez.strategy;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class EasterDiscounter implements Discounter {
|
||||
|
||||
@Override
|
||||
public BigDecimal apply(BigDecimal amount) {
|
||||
return amount.multiply(BigDecimal.valueOf(0.5));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
package com.ossez.streamreduce.application;
|
||||
|
||||
import com.ossez.streamreduce.entities.User;
|
||||
import com.ossez.streamreduce.utilities.NumberUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
int result1 = numbers.stream().reduce(0, (a, b) -> a + b);
|
||||
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("", (a, b) -> a + b);
|
||||
System.out.println(result3);
|
||||
|
||||
String result4 = letters.stream().reduce("", String::concat);
|
||||
System.out.println(result4);
|
||||
|
||||
String result5 = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.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);
|
||||
|
||||
List<User> userList = new ArrayList<>();
|
||||
for (int i = 0; i <= 1000000; i++) {
|
||||
userList.add(new User("John" + i, i));
|
||||
}
|
||||
|
||||
long t1 = System.currentTimeMillis();
|
||||
int result9 = userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
long t2 = System.currentTimeMillis();
|
||||
System.out.println(result9);
|
||||
System.out.println("Sequential stream time: " + (t2 - t1) + "ms");
|
||||
|
||||
long t3 = System.currentTimeMillis();
|
||||
int result10 = userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
long t4 = System.currentTimeMillis();
|
||||
System.out.println(result10);
|
||||
System.out.println("Parallel stream time: " + (t4 - t3) + "ms");
|
||||
|
||||
int result11 = NumberUtils.divideListElements(numbers, 1);
|
||||
System.out.println(result11);
|
||||
|
||||
int result12 = NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 0);
|
||||
System.out.println(result12);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.ossez.streamreduce.entities;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Rating {
|
||||
|
||||
double points;
|
||||
List<Review> reviews = new ArrayList<>();
|
||||
|
||||
public Rating() {}
|
||||
|
||||
public void add(Review review) {
|
||||
reviews.add(review);
|
||||
computeRating();
|
||||
}
|
||||
|
||||
private double computeRating() {
|
||||
double totalPoints = reviews.stream().map(Review::getPoints).reduce(0, Integer::sum);
|
||||
this.points = totalPoints / reviews.size();
|
||||
return this.points;
|
||||
}
|
||||
|
||||
public static Rating average(Rating r1, Rating r2) {
|
||||
Rating combined = new Rating();
|
||||
combined.reviews = new ArrayList<>(r1.reviews);
|
||||
combined.reviews.addAll(r2.reviews);
|
||||
combined.computeRating();
|
||||
return combined;
|
||||
}
|
||||
|
||||
public double getPoints() {
|
||||
return points;
|
||||
}
|
||||
|
||||
public List<Review> getReviews() {
|
||||
return reviews;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.ossez.streamreduce.entities;
|
||||
|
||||
public class Review {
|
||||
|
||||
int points;
|
||||
String review;
|
||||
|
||||
public Review(int points, String review) {
|
||||
this.points = points;
|
||||
this.review = review;
|
||||
}
|
||||
|
||||
public int getPoints() {
|
||||
return points;
|
||||
}
|
||||
|
||||
public void setPoints(int points) {
|
||||
this.points = points;
|
||||
}
|
||||
|
||||
public String getReview() {
|
||||
return review;
|
||||
}
|
||||
|
||||
public void setReview(String review) {
|
||||
this.review = review;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.ossez.streamreduce.entities;
|
||||
|
||||
public class User {
|
||||
|
||||
private final String name;
|
||||
private final int age;
|
||||
private final Rating rating = new Rating();
|
||||
|
||||
public User(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public Rating getRating() {
|
||||
return rating;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "User{" + "name=" + name + ", age=" + age + '}';
|
||||
}
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.ossez.streamreduce.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,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="TRACE">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -0,0 +1,110 @@
|
|||
package com.ossez.internationalization;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.DateFormatSymbols;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class DateFormatUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenLocaleSpecificDateInstance_givenLanguageSpecificMonths() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat itInstance = DateFormat.getDateInstance(DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat usInstance = DateFormat.getDateInstance(DateFormat.FULL, Locale.US);
|
||||
|
||||
Assert.assertEquals("giovedì 1 febbraio 2018", itInstance.format(date));
|
||||
Assert.assertEquals("Thursday, February 1, 2018", usInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenDateInstanceWithDifferentFormats_givenSpecificDateFormatting() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat fullInstance = DateFormat.getDateInstance(DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat mediumInstance = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ITALY);
|
||||
|
||||
Assert.assertEquals("giovedì 1 febbraio 2018", fullInstance.format(date));
|
||||
Assert.assertEquals("1-feb-2018", mediumInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenTimeInstanceWithDifferentFormats_givenSpecificTimeFormatting() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat fullInstance = DateFormat.getTimeInstance(DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat mediumInstance = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ITALY);
|
||||
|
||||
Assert.assertEquals("10.15.20 CET", fullInstance.format(date));
|
||||
Assert.assertEquals("10.15.20" , mediumInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenDateTimeInstanceWithDifferentFormats_givenSpecificDateTimeFormatting() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat ffInstance = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat smInstance = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.ITALY);
|
||||
|
||||
Assert.assertEquals("giovedì 1 febbraio 2018 10.15.20 CET", ffInstance.format(date));
|
||||
Assert.assertEquals("01/02/18 10.15.20", smInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenLocaleSpecificDateTimeInstance_givenLocaleSpecificFormatting() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
gregorianCalendar.setTimeZone(TimeZone.getTimeZone("CET"));
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
|
||||
Date date = gregorianCalendar.getTime();
|
||||
|
||||
DateFormat itInstance = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.ITALY);
|
||||
DateFormat jpInstance = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.JAPAN);
|
||||
|
||||
Assert.assertEquals("giovedì 1 febbraio 2018 10.15.20 CET", itInstance.format(date));
|
||||
Assert.assertEquals("2018年2月1日 10時15分20秒 CET", jpInstance.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenCustomizedSimpleDateFormat_thenSpecificMonthRepresentations() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
Date date = gregorianCalendar.getTime();
|
||||
Locale.setDefault(new Locale("pl", "PL"));
|
||||
|
||||
SimpleDateFormat fullMonthDateFormat = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss:SSS");
|
||||
SimpleDateFormat shortMonthsimpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:SSS");
|
||||
|
||||
Assert.assertEquals("01-lutego-2018 10:15:20:000", fullMonthDateFormat.format(date));
|
||||
Assert.assertEquals("01-02-2018 10:15:20:000" , shortMonthsimpleDateFormat.format(date));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGregorianCalendar_whenCustomizedDateFormatSymbols_thenChangedDayNames() {
|
||||
GregorianCalendar gregorianCalendar = new GregorianCalendar(2018, 1, 1, 10, 15, 20);
|
||||
Date date = gregorianCalendar.getTime();
|
||||
Locale.setDefault(new Locale("pl", "PL"));
|
||||
|
||||
DateFormatSymbols dateFormatSymbols = new DateFormatSymbols();
|
||||
dateFormatSymbols.setWeekdays(new String[]{"A", "B", "C", "D", "E", "F", "G", "H"});
|
||||
SimpleDateFormat standardDateFormat = new SimpleDateFormat("EEEE-MMMM-yyyy HH:mm:ss:SSS");
|
||||
SimpleDateFormat newDaysDateFormat = new SimpleDateFormat("EEEE-MMMM-yyyy HH:mm:ss:SSS", dateFormatSymbols);
|
||||
|
||||
Assert.assertEquals("czwartek-lutego-2018 10:15:20:000", standardDateFormat.format(date));
|
||||
Assert.assertEquals("F-lutego-2018 10:15:20:000", newDaysDateFormat.format(date));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,76 @@
|
|||
package com.ossez.internationalization;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.DecimalFormatSymbols;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.Currency;
|
||||
import java.util.Locale;
|
||||
|
||||
public class NumbersCurrenciesFormattingUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDifferentLocalesAndDoubleNumber_whenNumberInstance_thenDifferentOutput() {
|
||||
Locale usLocale = Locale.US;
|
||||
Locale plLocale = new Locale("pl", "PL");
|
||||
Locale deLocale = Locale.GERMANY;
|
||||
double number = 102_300.456d;
|
||||
|
||||
NumberFormat usNumberFormat = NumberFormat.getInstance(usLocale);
|
||||
NumberFormat plNumberFormat = NumberFormat.getInstance(plLocale);
|
||||
NumberFormat deNumberFormat = NumberFormat.getInstance(deLocale);
|
||||
|
||||
Assert.assertEquals(usNumberFormat.format(number), "102,300.456");
|
||||
Assert.assertEquals(plNumberFormat.format(number), "102 300,456");
|
||||
Assert.assertEquals(deNumberFormat.format(number), "102.300,456");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDifferentLocalesAndDoubleAmount_whenCurrencyInstance_thenDifferentOutput() {
|
||||
Locale usLocale = Locale.US;
|
||||
Locale plLocale = new Locale("pl", "PL");
|
||||
Locale deLocale = Locale.GERMANY;
|
||||
BigDecimal number = new BigDecimal(102_300.456d);
|
||||
|
||||
NumberFormat usNumberFormat = NumberFormat.getCurrencyInstance(usLocale);
|
||||
NumberFormat plNumberFormat = NumberFormat.getCurrencyInstance(plLocale);
|
||||
NumberFormat deNumberFormat = NumberFormat.getCurrencyInstance(deLocale);
|
||||
|
||||
Assert.assertEquals(usNumberFormat.format(number), "$102,300.46");
|
||||
Assert.assertEquals(plNumberFormat.format(number), "102 300,46 zł");
|
||||
Assert.assertEquals(deNumberFormat.format(number), "102.300,46 €");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocaleAndNumber_whenSpecificDecimalFormat_thenSpecificOutput() {
|
||||
Locale.setDefault(Locale.FRANCE);
|
||||
BigDecimal number = new BigDecimal(102_300.456d);
|
||||
|
||||
DecimalFormat zeroDecimalFormat = new DecimalFormat("000000000.0000");
|
||||
DecimalFormat hashDecimalFormat = new DecimalFormat("###,###.#");
|
||||
DecimalFormat dollarDecimalFormat = new DecimalFormat("$###,###.##");
|
||||
|
||||
Assert.assertEquals(zeroDecimalFormat.format(number), "000102300,4560");
|
||||
Assert.assertEquals(hashDecimalFormat.format(number), "102 300,5");
|
||||
Assert.assertEquals(dollarDecimalFormat.format(number), "$102 300,46");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocaleAndNumber_whenSpecificDecimalFormatSymbols_thenSpecificOutput() {
|
||||
Locale.setDefault(Locale.FRANCE);
|
||||
BigDecimal number = new BigDecimal(102_300.456d);
|
||||
|
||||
DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance();
|
||||
decimalFormatSymbols.setGroupingSeparator('^');
|
||||
decimalFormatSymbols.setDecimalSeparator('@');
|
||||
DecimalFormat separatorsDecimalFormat = new DecimalFormat("$###,###.##");
|
||||
separatorsDecimalFormat.setGroupingSize(4);
|
||||
separatorsDecimalFormat.setCurrency(Currency.getInstance(Locale.JAPAN));
|
||||
separatorsDecimalFormat.setDecimalFormatSymbols(decimalFormatSymbols);
|
||||
|
||||
Assert.assertEquals(separatorsDecimalFormat.format(number), "$10^2300@46");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.ossez.java8;
|
||||
|
||||
import com.ossez.java_8_features.Vehicle;
|
||||
import com.ossez.java_8_features.VehicleImpl;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Java8DefaultStaticIntefaceMethodsUnitTest {
|
||||
|
||||
@Test
|
||||
public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() {
|
||||
Vehicle vehicle = new VehicleImpl();
|
||||
String overview = vehicle.getOverview();
|
||||
long[] startPosition = vehicle.startPosition();
|
||||
|
||||
assertEquals(overview, "ATV made by N&F Vehicles");
|
||||
assertEquals(startPosition[0], 23);
|
||||
assertEquals(startPosition[1], 15);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void callDefaultInterfaceMethods_whenExpectedResults_thenCorrect() {
|
||||
String producer = Vehicle.producer();
|
||||
assertEquals(producer, "N&F Vehicles");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,133 @@
|
|||
package com.ossez.java8;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Java8ForEachUnitTest {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(Java8ForEachUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void compareForEachMethods_thenPrintResults() {
|
||||
|
||||
List<String> names = new ArrayList<>();
|
||||
names.add("Larry");
|
||||
names.add("Steve");
|
||||
names.add("James");
|
||||
names.add("Conan");
|
||||
names.add("Ellen");
|
||||
|
||||
// Java 5 - for-loop
|
||||
logger.debug("--- Enhanced for-loop ---");
|
||||
for (String name : names) {
|
||||
logger.debug(name);
|
||||
}
|
||||
|
||||
// Java 8 - forEach
|
||||
names.forEach(name -> {
|
||||
System.out.println(name);
|
||||
});
|
||||
|
||||
logger.debug("--- Print Consumer ---");
|
||||
Consumer<String> printConsumer = new Consumer<String>() {
|
||||
public void accept(String name) {
|
||||
System.out.println(name);
|
||||
}
|
||||
|
||||
;
|
||||
};
|
||||
|
||||
names.forEach(printConsumer);
|
||||
|
||||
// Anonymous inner class that implements Consumer interface
|
||||
logger.debug("--- Anonymous inner class ---");
|
||||
names.forEach(new Consumer<String>() {
|
||||
public void accept(String name) {
|
||||
logger.debug(name);
|
||||
}
|
||||
});
|
||||
|
||||
// Java 8 - forEach - Lambda Syntax
|
||||
logger.debug("--- forEach method ---");
|
||||
names.forEach(name -> logger.debug(name));
|
||||
|
||||
// Java 8 - forEach - Print elements using a Method Reference
|
||||
logger.debug("--- Method Reference ---");
|
||||
names.forEach(logger::debug);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_thenIterateAndPrintResults() {
|
||||
List<String> names = Arrays.asList("Larry", "Steve", "James");
|
||||
|
||||
names.forEach(System.out::println);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_thenIterateAndPrintResults() {
|
||||
Set<String> uniqueNames = new HashSet<>(Arrays.asList("Larry", "Steve", "James"));
|
||||
|
||||
uniqueNames.forEach(System.out::println);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenQueue_thenIterateAndPrintResults() {
|
||||
Queue<String> namesQueue = new ArrayDeque<>(Arrays.asList("Larry", "Steve", "James"));
|
||||
|
||||
namesQueue.forEach(System.out::println);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMap_thenIterateAndPrintResults() {
|
||||
Map<Integer, String> namesMap = new HashMap<>();
|
||||
namesMap.put(1, "Larry");
|
||||
namesMap.put(2, "Steve");
|
||||
namesMap.put(3, "James");
|
||||
|
||||
namesMap.entrySet()
|
||||
.forEach(entry -> System.out.println(entry.getKey() + " " + entry.getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMap_whenUsingBiConsumer_thenIterateAndPrintResults2() {
|
||||
Map<Integer, String> namesMap = new HashMap<>();
|
||||
namesMap.put(1, "Larry");
|
||||
namesMap.put(2, "Steve");
|
||||
namesMap.put(3, "James");
|
||||
|
||||
namesMap.forEach((key, value) -> System.out.println(key + " " + value));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIteratorAndFor() {
|
||||
List<String> testList = Arrays.asList("A", "B", "C");
|
||||
|
||||
Iterator iterator = testList.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
logger.debug((String) iterator.next());
|
||||
|
||||
}
|
||||
|
||||
logger.debug("--- FOR ---");
|
||||
for (int i = 0; i < testList.size(); i++) {
|
||||
logger.debug("{} > {}", i, testList.get(i));
|
||||
}
|
||||
|
||||
logger.debug("--- FOR LOOP ---");
|
||||
for (String s : testList) {
|
||||
logger.debug(s);
|
||||
}
|
||||
|
||||
logger.debug("--- FOR EACH ---");
|
||||
testList.forEach(s -> {
|
||||
logger.debug(s);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package com.ossez.java8;
|
||||
|
||||
import com.ossez.java_8_features.User;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class Java8MethodReferenceUnitTest {
|
||||
|
||||
private List<String> list;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
list = new ArrayList<>();
|
||||
list.add("One");
|
||||
list.add("OneAndOnly");
|
||||
list.add("Derek");
|
||||
list.add("Change");
|
||||
list.add("factory");
|
||||
list.add("justBefore");
|
||||
list.add("Italy");
|
||||
list.add("Italy");
|
||||
list.add("Thursday");
|
||||
list.add("");
|
||||
list.add("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkStaticMethodReferences_whenWork_thenCorrect() {
|
||||
|
||||
List<User> users = new ArrayList<>();
|
||||
users.add(new User());
|
||||
users.add(new User());
|
||||
boolean isReal = users.stream().anyMatch(u -> User.isRealUser(u));
|
||||
boolean isRealRef = users.stream().anyMatch(User::isRealUser);
|
||||
assertTrue(isReal);
|
||||
assertTrue(isRealRef);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkInstanceMethodReferences_whenWork_thenCorrect() {
|
||||
User user = new User();
|
||||
boolean isLegalName = list.stream().anyMatch(user::isLegalName);
|
||||
assertTrue(isLegalName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkParticularTypeReferences_whenWork_thenCorrect() {
|
||||
long count = list.stream().filter(String::isEmpty).count();
|
||||
assertEquals(count, 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkConstructorReferences_whenWork_thenCorrect() {
|
||||
Stream<User> stream = list.stream().map(User::new);
|
||||
List<User> userList = stream.collect(Collectors.toList());
|
||||
assertEquals(userList.size(), list.size());
|
||||
assertTrue(userList.get(0) instanceof User);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,116 @@
|
|||
package com.ossez.java8;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.ossez.java_8_features.Address;
|
||||
import com.ossez.java_8_features.CustomException;
|
||||
import com.ossez.java_8_features.OptionalAddress;
|
||||
import com.ossez.java_8_features.OptionalUser;
|
||||
import com.ossez.java_8_features.User;
|
||||
|
||||
public class Java8OptionalUnitTest {
|
||||
|
||||
private List<String> list;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
list = new ArrayList<>();
|
||||
list.add("One");
|
||||
list.add("OneAndOnly");
|
||||
list.add("Derek");
|
||||
list.add("Change");
|
||||
list.add("factory");
|
||||
list.add("justBefore");
|
||||
list.add("Italy");
|
||||
list.add("Italy");
|
||||
list.add("Thursday");
|
||||
list.add("");
|
||||
list.add("");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void checkOptional_whenAsExpected_thenCorrect() {
|
||||
Optional<String> optionalEmpty = Optional.empty();
|
||||
assertFalse(optionalEmpty.isPresent());
|
||||
|
||||
String str = "value";
|
||||
Optional<String> optional = Optional.of(str);
|
||||
assertEquals(optional.get(), "value");
|
||||
|
||||
Optional<String> optionalNullable = Optional.ofNullable(str);
|
||||
Optional<String> optionalNull = Optional.ofNullable(null);
|
||||
assertEquals(optionalNullable.get(), "value");
|
||||
assertFalse(optionalNull.isPresent());
|
||||
|
||||
List<String> listOpt = Optional.of(list).orElse(new ArrayList<>());
|
||||
List<String> listNull = null;
|
||||
List<String> listOptNull = Optional.ofNullable(listNull).orElse(new ArrayList<>());
|
||||
assertTrue(listOpt == list);
|
||||
assertTrue(listOptNull.isEmpty());
|
||||
|
||||
Optional<User> user = Optional.ofNullable(getUser());
|
||||
String result = user.map(User::getAddress).map(Address::getStreet).orElse("not specified");
|
||||
assertEquals(result, "1st Avenue");
|
||||
|
||||
Optional<OptionalUser> optionalUser = Optional.ofNullable(getOptionalUser());
|
||||
String resultOpt = optionalUser.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified");
|
||||
assertEquals(resultOpt, "1st Avenue");
|
||||
|
||||
Optional<User> userNull = Optional.ofNullable(getUserNull());
|
||||
String resultNull = userNull.map(User::getAddress).map(Address::getStreet).orElse("not specified");
|
||||
assertEquals(resultNull, "not specified");
|
||||
|
||||
Optional<OptionalUser> optionalUserNull = Optional.ofNullable(getOptionalUserNull());
|
||||
String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified");
|
||||
assertEquals(resultOptNull, "not specified");
|
||||
|
||||
}
|
||||
|
||||
@Test(expected = CustomException.class)
|
||||
public void callMethod_whenCustomException_thenCorrect() {
|
||||
User user = new User();
|
||||
String result = user.getOrThrow();
|
||||
}
|
||||
|
||||
private User getUser() {
|
||||
User user = new User();
|
||||
Address address = new Address();
|
||||
address.setStreet("1st Avenue");
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
private OptionalUser getOptionalUser() {
|
||||
OptionalUser user = new OptionalUser();
|
||||
OptionalAddress address = new OptionalAddress();
|
||||
address.setStreet("1st Avenue");
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
private OptionalUser getOptionalUserNull() {
|
||||
OptionalUser user = new OptionalUser();
|
||||
OptionalAddress address = new OptionalAddress();
|
||||
address.setStreet(null);
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
private User getUserNull() {
|
||||
User user = new User();
|
||||
Address address = new Address();
|
||||
address.setStreet(null);
|
||||
user.setAddress(address);
|
||||
return user;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.ossez.java8.comparator;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.ToString;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@ToString
|
||||
@EqualsAndHashCode
|
||||
public class Employee implements Comparable<Employee>{
|
||||
String name;
|
||||
int age;
|
||||
double salary;
|
||||
long mobile;
|
||||
|
||||
@Override
|
||||
public int compareTo(Employee argEmployee) {
|
||||
return name.compareTo(argEmployee.getName());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,152 @@
|
|||
package com.ossez.java8.comparator;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class Java8ComparatorUnitTest {
|
||||
|
||||
private Employee[] employees;
|
||||
private Employee[] employeesArrayWithNulls;
|
||||
private Employee[] sortedEmployeesByName;
|
||||
private Employee[] sortedEmployeesByNameDesc;
|
||||
private Employee[] sortedEmployeesByAge;
|
||||
private Employee[] sortedEmployeesByMobile;
|
||||
private Employee[] sortedEmployeesBySalary;
|
||||
private Employee[] sortedEmployeesArray_WithNullsFirst;
|
||||
private Employee[] sortedEmployeesArray_WithNullsLast;
|
||||
private Employee[] sortedEmployeesByNameAge;
|
||||
private Employee[] someMoreEmployees;
|
||||
private Employee[] sortedEmployeesByAgeName;;
|
||||
|
||||
@Before
|
||||
public void initData() {
|
||||
employees = new Employee[] { new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
employeesArrayWithNulls = new Employee[] { new Employee("John", 25, 3000, 9922001), null, new Employee("Ace", 22, 2000, 5924001), null, new Employee("Keith", 35, 4000, 3924401) };
|
||||
|
||||
sortedEmployeesByName = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
sortedEmployeesByNameDesc = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("John", 25, 3000, 9922001), new Employee("Ace", 22, 2000, 5924001) };
|
||||
|
||||
sortedEmployeesByAge = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
|
||||
sortedEmployeesByMobile = new Employee[] { new Employee("Keith", 35, 4000, 3924401), new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), };
|
||||
|
||||
sortedEmployeesBySalary = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), };
|
||||
|
||||
sortedEmployeesArray_WithNullsFirst = new Employee[] { null, null, new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
sortedEmployeesArray_WithNullsLast = new Employee[] { new Employee("Ace", 22, 2000, 5924001), new Employee("John", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401), null, null };
|
||||
|
||||
someMoreEmployees = new Employee[] { new Employee("Jake", 25, 3000, 9922001), new Employee("Jake", 22, 2000, 5924001), new Employee("Ace", 22, 3000, 6423001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
|
||||
sortedEmployeesByAgeName = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
sortedEmployeesByNameAge = new Employee[] { new Employee("Ace", 22, 3000, 6423001), new Employee("Jake", 22, 2000, 5924001), new Employee("Jake", 25, 3000, 9922001), new Employee("Keith", 35, 4000, 3924401) };
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparing_thenSortedByName() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||
Arrays.sort(employees, employeeNameComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingWithComparator_thenSortedByNameDesc() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName, (s1, s2) -> {
|
||||
return s2.compareTo(s1);
|
||||
});
|
||||
Arrays.sort(employees, employeeNameComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReversed_thenSortedByNameDesc() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||
Comparator<Employee> employeeNameComparatorReversed = employeeNameComparator.reversed();
|
||||
Arrays.sort(employees, employeeNameComparatorReversed);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingInt_thenSortedByAge() {
|
||||
Comparator<Employee> employeeAgeComparator = Comparator.comparingInt(Employee::getAge);
|
||||
Arrays.sort(employees, employeeAgeComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByAge));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingLong_thenSortedByMobile() {
|
||||
Comparator<Employee> employeeMobileComparator = Comparator.comparingLong(Employee::getMobile);
|
||||
Arrays.sort(employees, employeeMobileComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByMobile));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenComparingDouble_thenSortedBySalary() {
|
||||
Comparator<Employee> employeeSalaryComparator = Comparator.comparingDouble(Employee::getSalary);
|
||||
Arrays.sort(employees, employeeSalaryComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesBySalary));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNaturalOrder_thenSortedByName() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.<Employee> naturalOrder();
|
||||
Arrays.sort(employees, employeeNameComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByName));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReverseOrder_thenSortedByNameDesc() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.<Employee> reverseOrder();
|
||||
Arrays.sort(employees, employeeNameComparator);
|
||||
// System.out.println(Arrays.toString(employees));
|
||||
assertTrue(Arrays.equals(employees, sortedEmployeesByNameDesc));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullsFirst_thenSortedByNameWithNullsFirst() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||
Comparator<Employee> employeeNameComparator_nullFirst = Comparator.nullsFirst(employeeNameComparator);
|
||||
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullFirst);
|
||||
// System.out.println(Arrays.toString(employeesArrayWithNulls));
|
||||
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsFirst));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNullsLast_thenSortedByNameWithNullsLast() {
|
||||
Comparator<Employee> employeeNameComparator = Comparator.comparing(Employee::getName);
|
||||
Comparator<Employee> employeeNameComparator_nullLast = Comparator.nullsLast(employeeNameComparator);
|
||||
Arrays.sort(employeesArrayWithNulls, employeeNameComparator_nullLast);
|
||||
// System.out.println(Arrays.toString(employeesArrayWithNulls));
|
||||
assertTrue(Arrays.equals(employeesArrayWithNulls, sortedEmployeesArray_WithNullsLast));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenThenComparing_thenSortedByAgeName() {
|
||||
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
|
||||
|
||||
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
|
||||
// System.out.println(Arrays.toString(someMoreEmployees));
|
||||
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByAgeName));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenThenComparing_thenSortedByNameAge() {
|
||||
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
|
||||
|
||||
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
|
||||
// System.out.println(Arrays.toString(someMoreEmployees));
|
||||
assertTrue(Arrays.equals(someMoreEmployees, sortedEmployeesByNameAge));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,215 @@
|
|||
package com.ossez.java_8_features.groupingby;
|
||||
|
||||
import static java.util.Comparator.comparingInt;
|
||||
import static java.util.stream.Collectors.averagingInt;
|
||||
import static java.util.stream.Collectors.counting;
|
||||
import static java.util.stream.Collectors.groupingBy;
|
||||
import static java.util.stream.Collectors.groupingByConcurrent;
|
||||
import static java.util.stream.Collectors.joining;
|
||||
import static java.util.stream.Collectors.mapping;
|
||||
import static java.util.stream.Collectors.maxBy;
|
||||
import static java.util.stream.Collectors.summarizingInt;
|
||||
import static java.util.stream.Collectors.summingInt;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static java.util.stream.Collectors.toSet;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumMap;
|
||||
import java.util.IntSummaryStatistics;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class Java8GroupingByCollectorUnitTest {
|
||||
|
||||
private static final List<BlogPost> posts = Arrays.asList(new BlogPost("News item 1", "Author 1", BlogPostType.NEWS, 15), new BlogPost("Tech review 1", "Author 2", BlogPostType.REVIEW, 5),
|
||||
new BlogPost("Programming guide", "Author 1", BlogPostType.GUIDE, 20), new BlogPost("News item 2", "Author 2", BlogPostType.NEWS, 35), new BlogPost("Tech review 2", "Author 1", BlogPostType.REVIEW, 15));
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByType_thenGetAMapBetweenTypeAndPosts() {
|
||||
Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndTheirTitlesAreJoinedInAString_thenGetAMapBetweenTypeAndCsvTitles() {
|
||||
Map<BlogPostType, String> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, mapping(BlogPost::getTitle, joining(", ", "Post titles: [", "]"))));
|
||||
|
||||
assertEquals("Post titles: [News item 1, News item 2]", postsPerType.get(BlogPostType.NEWS));
|
||||
assertEquals("Post titles: [Programming guide]", postsPerType.get(BlogPostType.GUIDE));
|
||||
assertEquals("Post titles: [Tech review 1, Tech review 2]", postsPerType.get(BlogPostType.REVIEW));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndSumTheLikes_thenGetAMapBetweenTypeAndPostLikes() {
|
||||
Map<BlogPostType, Integer> likesPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, summingInt(BlogPost::getLikes)));
|
||||
|
||||
assertEquals(50, likesPerType.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(20, likesPerType.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
assertEquals(20, likesPerType.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeInAnEnumMap_thenGetAnEnumMapBetweenTypeAndPosts() {
|
||||
EnumMap<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, () -> new EnumMap<>(BlogPostType.class), toList()));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeInSets_thenGetAMapBetweenTypesAndSetsOfPosts() {
|
||||
Map<BlogPostType, Set<BlogPost>> postsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, toSet()));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeConcurrently_thenGetAMapBetweenTypeAndPosts() {
|
||||
ConcurrentMap<BlogPostType, List<BlogPost>> postsPerType = posts.parallelStream()
|
||||
.collect(groupingByConcurrent(BlogPost::getType));
|
||||
|
||||
assertEquals(2, postsPerType.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, postsPerType.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(2, postsPerType.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndAveragingLikes_thenGetAMapBetweenTypeAndAverageNumberOfLikes() {
|
||||
Map<BlogPostType, Double> averageLikesPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, averagingInt(BlogPost::getLikes)));
|
||||
|
||||
assertEquals(25, averageLikesPerType.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(20, averageLikesPerType.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
assertEquals(10, averageLikesPerType.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndCounted_thenGetAMapBetweenTypeAndNumberOfPosts() {
|
||||
Map<BlogPostType, Long> numberOfPostsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, counting()));
|
||||
|
||||
assertEquals(2, numberOfPostsPerType.get(BlogPostType.NEWS)
|
||||
.intValue());
|
||||
assertEquals(1, numberOfPostsPerType.get(BlogPostType.GUIDE)
|
||||
.intValue());
|
||||
assertEquals(2, numberOfPostsPerType.get(BlogPostType.REVIEW)
|
||||
.intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndMaxingLikes_thenGetAMapBetweenTypeAndMaximumNumberOfLikes() {
|
||||
Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, maxBy(comparingInt(BlogPost::getLikes))));
|
||||
|
||||
assertTrue(maxLikesPerPostType.get(BlogPostType.NEWS)
|
||||
.isPresent());
|
||||
assertEquals(35, maxLikesPerPostType.get(BlogPostType.NEWS)
|
||||
.get()
|
||||
.getLikes());
|
||||
|
||||
assertTrue(maxLikesPerPostType.get(BlogPostType.GUIDE)
|
||||
.isPresent());
|
||||
assertEquals(20, maxLikesPerPostType.get(BlogPostType.GUIDE)
|
||||
.get()
|
||||
.getLikes());
|
||||
|
||||
assertTrue(maxLikesPerPostType.get(BlogPostType.REVIEW)
|
||||
.isPresent());
|
||||
assertEquals(15, maxLikesPerPostType.get(BlogPostType.REVIEW)
|
||||
.get()
|
||||
.getLikes());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByAuthorAndThenByType_thenGetAMapBetweenAuthorAndMapsBetweenTypeAndBlogPosts() {
|
||||
Map<String, Map<BlogPostType, List<BlogPost>>> map = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getAuthor, groupingBy(BlogPost::getType)));
|
||||
|
||||
assertEquals(1, map.get("Author 1")
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, map.get("Author 1")
|
||||
.get(BlogPostType.GUIDE)
|
||||
.size());
|
||||
assertEquals(1, map.get("Author 1")
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
|
||||
assertEquals(1, map.get("Author 2")
|
||||
.get(BlogPostType.NEWS)
|
||||
.size());
|
||||
assertEquals(1, map.get("Author 2")
|
||||
.get(BlogPostType.REVIEW)
|
||||
.size());
|
||||
assertNull(map.get("Author 2")
|
||||
.get(BlogPostType.GUIDE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByTypeAndSummarizingLikes_thenGetAMapBetweenTypeAndSummary() {
|
||||
Map<BlogPostType, IntSummaryStatistics> likeStatisticsPerType = posts.stream()
|
||||
.collect(groupingBy(BlogPost::getType, summarizingInt(BlogPost::getLikes)));
|
||||
|
||||
IntSummaryStatistics newsLikeStatistics = likeStatisticsPerType.get(BlogPostType.NEWS);
|
||||
|
||||
assertEquals(2, newsLikeStatistics.getCount());
|
||||
assertEquals(50, newsLikeStatistics.getSum());
|
||||
assertEquals(25.0, newsLikeStatistics.getAverage(), 0.001);
|
||||
assertEquals(35, newsLikeStatistics.getMax());
|
||||
assertEquals(15, newsLikeStatistics.getMin());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOfPosts_whenGroupedByComplexMapKeyType_thenGetAMapBetweenTupleAndList() {
|
||||
Map<Tuple, List<BlogPost>> postsPerTypeAndAuthor = posts.stream()
|
||||
.collect(groupingBy(post -> new Tuple(post.getType(), post.getAuthor())));
|
||||
|
||||
List<BlogPost> result = postsPerTypeAndAuthor.get(new Tuple(BlogPostType.GUIDE, "Author 1"));
|
||||
|
||||
assertThat(result.size()).isEqualTo(1);
|
||||
|
||||
BlogPost blogPost = result.get(0);
|
||||
|
||||
assertThat(blogPost.getTitle()).isEqualTo("Programming guide");
|
||||
assertThat(blogPost.getType()).isEqualTo(BlogPostType.GUIDE);
|
||||
assertThat(blogPost.getAuthor()).isEqualTo("Author 1");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.ossez.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();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,50 @@
|
|||
/*
|
||||
* 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.ossez.nullsafecollectionstreams;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
*
|
||||
* @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();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
|
||||
package com.ossez.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();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.ossez.spliteratorAPI;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Spliterator;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ExecutorUnitTest {
|
||||
Article article;
|
||||
Stream<Author> stream;
|
||||
Spliterator<Author> spliterator;
|
||||
Spliterator<Article> split1;
|
||||
Spliterator<Article> split2;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1),
|
||||
new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0),
|
||||
new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0),
|
||||
new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1),
|
||||
new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1),
|
||||
new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0);
|
||||
stream = article.getListOfAuthors().stream();
|
||||
split1 = Executor.generateElements().spliterator();
|
||||
split2 = split1.trySplit();
|
||||
spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAstreamOfAuthors_whenProcessedInParallelWithCustomSpliterator_coubtProducessRightOutput() {
|
||||
Stream<Author> stream2 = StreamSupport.stream(spliterator, true);
|
||||
assertThat(Executor.countAutors(stream2.parallel())).isEqualTo(9);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSpliterator_whenAppliedToAListOfArticle_thenSplittedInHalf() {
|
||||
assertThat(new Task(split1).call()).containsSequence(Executor.generateElements().size() / 2 + "");
|
||||
assertThat(new Task(split2).call()).containsSequence(Executor.generateElements().size() / 2 + "");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,72 @@
|
|||
package com.ossez.strategy;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StrategyDesignPatternUnitTest {
|
||||
@Test
|
||||
public void shouldDivideByTwo_WhenApplyingStaffDiscounter() {
|
||||
Discounter staffDiscounter = new EasterDiscounter();
|
||||
|
||||
final BigDecimal discountedValue = staffDiscounter
|
||||
.apply(BigDecimal.valueOf(100));
|
||||
|
||||
assertThat(discountedValue)
|
||||
.isEqualByComparingTo(BigDecimal.valueOf(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithAnonyousTypes() {
|
||||
Discounter staffDiscounter = new Discounter() {
|
||||
@Override
|
||||
public BigDecimal apply(BigDecimal amount) {
|
||||
return amount.multiply(BigDecimal.valueOf(0.5));
|
||||
}
|
||||
};
|
||||
|
||||
final BigDecimal discountedValue = staffDiscounter
|
||||
.apply(BigDecimal.valueOf(100));
|
||||
|
||||
assertThat(discountedValue)
|
||||
.isEqualByComparingTo(BigDecimal.valueOf(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldDivideByTwo_WhenApplyingStaffDiscounterWithLamda() {
|
||||
Discounter staffDiscounter = amount -> amount.multiply(BigDecimal.valueOf(0.5));
|
||||
|
||||
final BigDecimal discountedValue = staffDiscounter
|
||||
.apply(BigDecimal.valueOf(100));
|
||||
|
||||
assertThat(discountedValue)
|
||||
.isEqualByComparingTo(BigDecimal.valueOf(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldApplyAllDiscounts() {
|
||||
List<Discounter> discounters = Arrays.asList(Discounter.christmas(), Discounter.newYear(), Discounter.easter());
|
||||
|
||||
BigDecimal amount = BigDecimal.valueOf(100);
|
||||
|
||||
final Discounter combinedDiscounter = discounters
|
||||
.stream()
|
||||
.reduce(v -> v, Discounter::combine);
|
||||
|
||||
combinedDiscounter.apply(amount);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldChainDiscounters() {
|
||||
final Function<BigDecimal, BigDecimal> combinedDiscounters = Discounter
|
||||
.christmas()
|
||||
.andThen(Discounter.newYear());
|
||||
|
||||
combinedDiscounters.apply(BigDecimal.valueOf(100));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,153 @@
|
|||
package com.ossez.streamreduce.tests;
|
||||
|
||||
import com.ossez.streamreduce.entities.Rating;
|
||||
import com.ossez.streamreduce.entities.Review;
|
||||
import com.ossez.streamreduce.entities.User;
|
||||
import com.ossez.streamreduce.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 StreamReduceManualTest {
|
||||
|
||||
@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 givenUserList_whenReduceWithGreaterAgeAccumulator_thenFindsOldest() {
|
||||
List<User> users = Arrays.asList(new User("John", 30), new User("Alex", 40), new User("Julie", 35));
|
||||
|
||||
User oldest = users.stream().reduce(users.get(0), (user1, user2) -> user1.getAge() >= user2.getAge() ? user1 : user2);
|
||||
|
||||
assertThat(oldest).isEqualTo(users.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserListWithRatings_whenReduceWithGreaterAgeAccumulator_thenFindsOldest() {
|
||||
User john = new User("John", 30);
|
||||
john.getRating().add(new Review(5, ""));
|
||||
john.getRating().add(new Review(3, "not bad"));
|
||||
User julie = new User("Julie", 35);
|
||||
john.getRating().add(new Review(4, "great!"));
|
||||
john.getRating().add(new Review(2, "terrible experience"));
|
||||
john.getRating().add(new Review(4, ""));
|
||||
List<User> users = Arrays.asList(john, julie);
|
||||
|
||||
Rating averageRating = users.stream().reduce(new Rating(), (rating, user) -> Rating.average(rating, user.getRating()), Rating::average);
|
||||
|
||||
assertThat(averageRating.getPoints()).isEqualTo(3.6);
|
||||
}
|
||||
|
||||
@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 givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlockAndListContainsZero_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6);
|
||||
|
||||
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlockAndDividerIsZero_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
|
||||
assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 0)).isEqualTo(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
|
||||
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
|
||||
|
||||
assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoStreams_whenCalledReduceOnParallelizedStream_thenFasterExecutionTime() {
|
||||
List<User> userList = new ArrayList<>();
|
||||
for (int i = 0; i <= 1000000; i++) {
|
||||
userList.add(new User("John" + i, i));
|
||||
}
|
||||
long currentTime1 = System.currentTimeMillis();
|
||||
userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
long sequentialExecutionTime = System.currentTimeMillis() -currentTime1;
|
||||
long currentTime2 = System.currentTimeMillis();
|
||||
userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
|
||||
long parallelizedExecutionTime = System.currentTimeMillis() - currentTime2;
|
||||
|
||||
assertThat(parallelizedExecutionTime).isLessThan(sequentialExecutionTime);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
package com.ossez.typeinference;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class TypeInferenceUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenNoTypeInference_whenInvokingGenericMethodsWithTypeParameters_ObjectsAreCreated() {
|
||||
// Without type inference. code is verbose.
|
||||
Map<String, Map<String, String>> mapOfMaps = new HashMap<String, Map<String, String>>();
|
||||
List<String> strList = Collections.<String> emptyList();
|
||||
List<Integer> intList = Collections.<Integer> emptyList();
|
||||
|
||||
assertTrue(mapOfMaps.isEmpty());
|
||||
assertTrue(strList.isEmpty());
|
||||
assertTrue(intList.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTypeInference_whenInvokingGenericMethodsWithoutTypeParameters_ObjectsAreCreated() {
|
||||
// With type inference. code is concise.
|
||||
List<String> strListInferred = Collections.emptyList();
|
||||
List<Integer> intListInferred = Collections.emptyList();
|
||||
|
||||
assertTrue(strListInferred.isEmpty());
|
||||
assertTrue(intListInferred.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJava7_whenInvokingCostructorWithoutTypeParameters_ObjectsAreCreated() {
|
||||
// Type Inference for constructor using diamond operator.
|
||||
Map<String, Map<String, String>> mapOfMapsInferred = new HashMap<>();
|
||||
|
||||
assertTrue(mapOfMapsInferred.isEmpty());
|
||||
assertEquals("public class java.util.HashMap<K,V>", mapOfMapsInferred.getClass()
|
||||
.toGenericString());
|
||||
}
|
||||
|
||||
static <T> List<T> add(List<T> list, T a, T b) {
|
||||
list.add(a);
|
||||
list.add(b);
|
||||
return list;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGenericMethod_WhenInvokedWithoutExplicitTypes_TypesAreInferred() {
|
||||
// Generalized target-type inference
|
||||
List<String> strListGeneralized = add(new ArrayList<>(), "abc", "def");
|
||||
List<Integer> intListGeneralized = add(new ArrayList<>(), 1, 2);
|
||||
List<Number> numListGeneralized = add(new ArrayList<>(), 1, 2.0);
|
||||
|
||||
assertEquals("public class java.util.ArrayList<E>", strListGeneralized.getClass()
|
||||
.toGenericString());
|
||||
assertFalse(intListGeneralized.isEmpty());
|
||||
assertEquals(2, numListGeneralized.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLambdaExpressions_whenParameterTypesNotSpecified_ParameterTypesAreInferred() {
|
||||
// Type Inference and Lambda Expressions.
|
||||
List<Integer> intList = Arrays.asList(5, 3, 4, 2, 1);
|
||||
Collections.sort(intList, (a, b) -> {
|
||||
assertEquals("java.lang.Integer", a.getClass().getName());
|
||||
return a.compareTo(b);
|
||||
});
|
||||
assertEquals("[1, 2, 3, 4, 5]", Arrays.toString(intList.toArray()));
|
||||
|
||||
List<String> strList = Arrays.asList("Red", "Blue", "Green");
|
||||
Collections.sort(strList, (a, b) -> {
|
||||
assertEquals("java.lang.String", a.getClass().getName());
|
||||
return a.compareTo(b);
|
||||
});
|
||||
assertEquals("[Blue, Green, Red]", Arrays.toString(strList.toArray()));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.ossez.util;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoField;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CurrentDateTimeUnitTest {
|
||||
|
||||
private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
|
||||
|
||||
@Test
|
||||
public void shouldReturnCurrentDate() {
|
||||
final LocalDate now = LocalDate.now(clock);
|
||||
|
||||
assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
|
||||
assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR));
|
||||
assertEquals(2016, now.get(ChronoField.YEAR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnCurrentTime() {
|
||||
final LocalTime now = LocalTime.now(clock);
|
||||
|
||||
assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
|
||||
assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR));
|
||||
assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturnCurrentTimestamp() {
|
||||
final Instant now = Instant.now(clock);
|
||||
|
||||
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
|
@ -3,15 +3,15 @@
|
|||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.ossez</groupId>
|
||||
<artifactId>core-java-annotations</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-annotations</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.ossez</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
<groupId>com.ossez.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.2-SNAPSHOT</version>
|
||||
<relativePath></relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -73,7 +73,7 @@
|
|||
|
||||
<properties>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<assertj.version>3.17.2</assertj.version>
|
||||
<asspectj.version>1.8.9</asspectj.version>
|
||||
<jmh-core.version>1.19</jmh-core.version>
|
||||
<jmh-generator.version>1.19</jmh-generator.version>
|
||||
|
|
|
@ -0,0 +1,15 @@
|
|||
## Core Java Collections List
|
||||
|
||||
This module contains articles about the Java List collection
|
||||
|
||||
### Relevant Articles:
|
||||
- [Java – Get Random Item/Element From a List](http://www.baeldung.com/java-random-list-element)
|
||||
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
|
||||
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
|
||||
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
|
||||
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
|
||||
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
|
||||
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
|
||||
- [[Next -->]](/core-java-modules/core-java-collections-list-2)
|
|
@ -0,0 +1,31 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-collections-list</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<name>core-java-collections-list</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.ossez.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.2-SNAPSHOT</version>
|
||||
<relativePath></relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,37 @@
|
|||
package com.ossez.findanelement;
|
||||
|
||||
public class Customer {
|
||||
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public Customer(int id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return id * 20;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof Customer) {
|
||||
Customer otherCustomer = (Customer) obj;
|
||||
if (id == otherCustomer.id)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
package com.ossez.findanelement;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.collections4.IterableUtils;
|
||||
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.collect.Iterables;
|
||||
|
||||
public class FindACustomerInGivenList {
|
||||
|
||||
public Customer findUsingGivenIndex(int indexOfCustomer, List<Customer> customers) {
|
||||
if (indexOfCustomer >= 0 && indexOfCustomer < customers.size())
|
||||
return customers.get(indexOfCustomer);
|
||||
return null;
|
||||
}
|
||||
|
||||
public int findUsingIndexOf(Customer customer, List<Customer> customers) {
|
||||
return customers.indexOf(customer);
|
||||
}
|
||||
|
||||
public boolean findUsingContains(Customer customer, List<Customer> customers) {
|
||||
return customers.contains(customer);
|
||||
}
|
||||
|
||||
public Customer findUsingIterator(String name, List<Customer> customers) {
|
||||
Iterator<Customer> iterator = customers.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Customer customer = iterator.next();
|
||||
if (customer.getName().equals(name)) {
|
||||
return customer;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Customer findUsingEnhancedForLoop(String name, List<Customer> customers) {
|
||||
for (Customer customer : customers) {
|
||||
if (customer.getName().equals(name)) {
|
||||
return customer;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Customer findUsingStream(String name, List<Customer> customers) {
|
||||
return customers.stream()
|
||||
.filter(customer -> customer.getName().equals(name))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public Customer findUsingParallelStream(String name, List<Customer> customers) {
|
||||
return customers.parallelStream()
|
||||
.filter(customer -> customer.getName().equals(name))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public Customer findUsingGuava(String name, List<Customer> customers) {
|
||||
return Iterables.tryFind(customers, new Predicate<Customer>() {
|
||||
public boolean apply(Customer customer) {
|
||||
return customer.getName().equals(name);
|
||||
}
|
||||
}).orNull();
|
||||
}
|
||||
|
||||
public Customer findUsingApacheCommon(String name, List<Customer> customers) {
|
||||
return IterableUtils.find(customers, new org.apache.commons.collections4.Predicate<Customer>() {
|
||||
public boolean evaluate(Customer customer) {
|
||||
return customer.getName().equals(name);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,210 @@
|
|||
package com.ossez.java.list;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
public class CustomList<E> implements List<E> {
|
||||
private Object[] internal = {};
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
// the first cycle
|
||||
// return true;
|
||||
|
||||
// the second cycle
|
||||
// if (internal.length != 0) {
|
||||
// return false;
|
||||
// } else {
|
||||
// return true;
|
||||
// }
|
||||
|
||||
// refactoring
|
||||
return internal.length == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
// the first cycle
|
||||
// if (isEmpty()) {
|
||||
// return 0;
|
||||
// } else {
|
||||
// return internal.length;
|
||||
// }
|
||||
|
||||
// refactoring
|
||||
return internal.length;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public E get(int index) {
|
||||
// the first cycle
|
||||
// return (E) internal[0];
|
||||
|
||||
// improvement
|
||||
return (E) internal[index];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean add(E element) {
|
||||
// the first cycle
|
||||
// internal = new Object[] { element };
|
||||
// return true;
|
||||
|
||||
// the second cycle
|
||||
Object[] temp = Arrays.copyOf(internal, internal.length + 1);
|
||||
temp[internal.length] = element;
|
||||
internal = temp;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(int index, E element) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addAll(Collection<? extends E> collection) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addAll(int index, Collection<? extends E> collection) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public E remove(int index) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object object) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeAll(Collection<?> collection) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retainAll(Collection<?> collection) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(Object object) {
|
||||
for (Object element : internal) {
|
||||
if (object.equals(element)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean containsAll(Collection<?> collection) {
|
||||
for (Object element : collection)
|
||||
if (!contains(element)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public E set(int index, E element) {
|
||||
E oldElement = (E) internal[index];
|
||||
internal[index] = element;
|
||||
return oldElement;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
internal = new Object[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public int indexOf(Object object) {
|
||||
for (int i = 0; i < internal.length; i++) {
|
||||
if (object.equals(internal[i])) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int lastIndexOf(Object object) {
|
||||
for (int i = internal.length - 1; i >= 0; i--) {
|
||||
if (object.equals(internal[i])) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public List<E> subList(int fromIndex, int toIndex) {
|
||||
Object[] temp = new Object[toIndex - fromIndex];
|
||||
System.arraycopy(internal, fromIndex, temp, 0, temp.length);
|
||||
return (List<E>) Arrays.asList(temp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] toArray() {
|
||||
return Arrays.copyOf(internal, internal.length);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public <T> T[] toArray(T[] array) {
|
||||
if (array.length < internal.length) {
|
||||
return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
|
||||
}
|
||||
|
||||
System.arraycopy(internal, 0, array, 0, internal.length);
|
||||
if (array.length > internal.length) {
|
||||
array[internal.length] = null;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<E> iterator() {
|
||||
return new CustomIterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListIterator<E> listIterator() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListIterator<E> listIterator(int index) {
|
||||
// ignored for brevity
|
||||
return null;
|
||||
}
|
||||
|
||||
private class CustomIterator implements Iterator<E> {
|
||||
int index;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return index != internal.length;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public E next() {
|
||||
E element = (E) CustomList.this.internal[index];
|
||||
index++;
|
||||
return element;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package com.ossez.java.list;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
import org.apache.commons.collections4.iterators.ReverseListIterator;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
/**
|
||||
* Provides methods for iterating backward over a list.
|
||||
*/
|
||||
public class ReverseIterator {
|
||||
|
||||
/**
|
||||
* Iterate using the for loop.
|
||||
*
|
||||
* @param list the list
|
||||
*/
|
||||
public void iterateUsingForLoop(final List<String> list) {
|
||||
|
||||
for (int i = list.size(); i-- > 0; ) {
|
||||
System.out.println(list.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate using the Java {@link ListIterator}.
|
||||
*
|
||||
* @param list the list
|
||||
*/
|
||||
public void iterateUsingListIterator(final List<String> list) {
|
||||
|
||||
final ListIterator listIterator = list.listIterator(list.size());
|
||||
while (listIterator.hasPrevious()) {
|
||||
System.out.println(listIterator.previous());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate using Java {@link Collections} API.
|
||||
*
|
||||
* @param list the list
|
||||
*/
|
||||
public void iterateUsingCollections(final List<String> list) {
|
||||
|
||||
Collections.reverse(list);
|
||||
for (final String item : list) {
|
||||
System.out.println(item);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate using Apache Commons {@link ReverseListIterator}.
|
||||
*
|
||||
* @param list the list
|
||||
*/
|
||||
public void iterateUsingApacheReverseListIterator(final List<String> list) {
|
||||
|
||||
final ReverseListIterator listIterator = new ReverseListIterator(list);
|
||||
while (listIterator.hasNext()) {
|
||||
System.out.println(listIterator.next());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate using Guava {@link Lists} API.
|
||||
*
|
||||
* @param list the list
|
||||
*/
|
||||
public void iterateUsingGuava(final List<String> list) {
|
||||
|
||||
final List<String> reversedList = Lists.reverse(list);
|
||||
for (final String item : reversedList) {
|
||||
System.out.println(item);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.ossez.java_8_features;
|
||||
|
||||
public class Car {
|
||||
|
||||
private String model;
|
||||
private int topSpeed;
|
||||
|
||||
public Car(String model, int topSpeed) {
|
||||
super();
|
||||
this.model = model;
|
||||
this.topSpeed = topSpeed;
|
||||
}
|
||||
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public void setModel(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public int getTopSpeed() {
|
||||
return topSpeed;
|
||||
}
|
||||
|
||||
public void setTopSpeed(int topSpeed) {
|
||||
this.topSpeed = topSpeed;
|
||||
}
|
||||
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.ossez.java_8_features;
|
||||
|
||||
public class Person {
|
||||
private String name;
|
||||
private Integer age;
|
||||
|
||||
public Person(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.ossez.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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.ossez.list.listoflist;
|
||||
|
||||
public class Pen implements Stationery {
|
||||
|
||||
public String name;
|
||||
|
||||
public Pen(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.ossez.list.listoflist;
|
||||
|
||||
public class Pencil implements Stationery{
|
||||
|
||||
public String name;
|
||||
|
||||
public Pencil(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.ossez.list.listoflist;
|
||||
|
||||
public class Rubber implements Stationery {
|
||||
|
||||
public String name;
|
||||
|
||||
public Rubber(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.ossez.list.listoflist;
|
||||
|
||||
public interface Stationery {
|
||||
|
||||
}
|
|
@ -0,0 +1,111 @@
|
|||
package com.ossez.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));
|
||||
}
|
||||
|
||||
}
|
|
@ -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>
|
|
@ -0,0 +1,105 @@
|
|||
package com.ossez.collections;
|
||||
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.containsInRelativeOrder;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.apache.commons.collections4.PredicateUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Predicates;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
|
||||
public class JavaCollectionCleanupUnitTest {
|
||||
|
||||
// tests - removing nulls
|
||||
|
||||
@Test
|
||||
public void givenListContainsNulls_whenRemovingNullsWithPlainJava_thenCorrect() {
|
||||
final List<Integer> list = Lists.newArrayList(null, 1, null);
|
||||
while (list.remove(null))
|
||||
;
|
||||
|
||||
assertThat(list, hasSize(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsNulls_whenRemovingNullsWithPlainJavaAlternative_thenCorrect() {
|
||||
final List<Integer> list = Lists.newArrayList(null, 1, null);
|
||||
list.removeAll(Collections.singleton(null));
|
||||
|
||||
assertThat(list, hasSize(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsNulls_whenRemovingNullsWithGuavaV1_thenCorrect() {
|
||||
final List<Integer> list = Lists.newArrayList(null, 1, null);
|
||||
Iterables.removeIf(list, Predicates.isNull());
|
||||
|
||||
assertThat(list, hasSize(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsNulls_whenRemovingNullsWithGuavaV2_thenCorrect() {
|
||||
final List<Integer> list = Lists.newArrayList(null, 1, null, 2, 3);
|
||||
final List<Integer> listWithoutNulls = Lists.newArrayList(Iterables.filter(list, Predicates.notNull()));
|
||||
|
||||
assertThat(listWithoutNulls, hasSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsNulls_whenRemovingNullsWithCommonsCollections_thenCorrect() {
|
||||
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
|
||||
CollectionUtils.filter(list, PredicateUtils.notNullPredicate());
|
||||
|
||||
assertThat(list, hasSize(3));
|
||||
}
|
||||
|
||||
// tests - remove duplicates
|
||||
|
||||
@Test
|
||||
public void givenListContainsDuplicates_whenRemovingDuplicatesWithPlainJava_thenCorrect() {
|
||||
final List<Integer> listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0);
|
||||
final List<Integer> listWithoutDuplicates = new ArrayList<>(new HashSet<>(listWithDuplicates));
|
||||
|
||||
assertThat(listWithoutDuplicates, hasSize(5));
|
||||
assertThat(listWithoutDuplicates, containsInAnyOrder(5, 0, 3, 1, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsDuplicates_whenRemovingDuplicatesPreservingOrderWithPlainJava_thenCorrect() {
|
||||
final List<Integer> listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0);
|
||||
final List<Integer> listWithoutDuplicates = new ArrayList<>(new LinkedHashSet<>(listWithDuplicates));
|
||||
|
||||
assertThat(listWithoutDuplicates, hasSize(5));
|
||||
assertThat(listWithoutDuplicates, containsInRelativeOrder(5, 0, 3, 1, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsDuplicates_whenRemovingDuplicatesWithGuava_thenCorrect() {
|
||||
final List<Integer> listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0);
|
||||
final List<Integer> listWithoutDuplicates = Lists.newArrayList(Sets.newHashSet(listWithDuplicates));
|
||||
|
||||
assertThat(listWithoutDuplicates, hasSize(5));
|
||||
assertThat(listWithoutDuplicates, containsInAnyOrder(5, 0, 3, 1, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsDuplicates_whenRemovingDuplicatesPreservingOrderWithGuava_thenCorrect() {
|
||||
final List<Integer> listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0);
|
||||
final List<Integer> listWithoutDuplicates = Lists.newArrayList(Sets.newLinkedHashSet(listWithDuplicates));
|
||||
|
||||
assertThat(listWithoutDuplicates, hasSize(5));
|
||||
assertThat(listWithoutDuplicates, containsInRelativeOrder(5, 0, 3, 1, 2));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,158 @@
|
|||
package com.ossez.findanelement;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FindACustomerInGivenListUnitTest {
|
||||
|
||||
private static List<Customer> customers = new ArrayList<>();
|
||||
|
||||
static {
|
||||
customers.add(new Customer(1, "Jack"));
|
||||
customers.add(new Customer(2, "James"));
|
||||
customers.add(new Customer(3, "Sam"));
|
||||
}
|
||||
|
||||
private static FindACustomerInGivenList findACustomerInGivenList = new FindACustomerInGivenList();
|
||||
|
||||
@Test
|
||||
public void givenAnIndex_whenFoundUsingGivenIndex_thenReturnCustomer() {
|
||||
Customer customer = findACustomerInGivenList.findUsingGivenIndex(0, customers);
|
||||
|
||||
assertEquals(1, customer.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIndex_whenNotFoundUsingGivenIndex_thenReturnNull() {
|
||||
Customer customer = findACustomerInGivenList.findUsingGivenIndex(5, customers);
|
||||
|
||||
assertNull(customer);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACustomer_whenFoundUsingContains_thenReturnTrue() {
|
||||
Customer james = new Customer(2, "James");
|
||||
boolean isJamesPresent = findACustomerInGivenList.findUsingContains(james, customers);
|
||||
|
||||
assertEquals(true, isJamesPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACustomer_whenNotFoundUsingContains_thenReturnFalse() {
|
||||
Customer john = new Customer(5, "John");
|
||||
boolean isJohnPresent = findACustomerInGivenList.findUsingContains(john, customers);
|
||||
|
||||
assertEquals(false, isJohnPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACustomer_whenFoundUsingIndexOf_thenReturnItsIndex() {
|
||||
Customer james = new Customer(2, "James");
|
||||
int indexOfJames = findACustomerInGivenList.findUsingIndexOf(james, customers);
|
||||
|
||||
assertEquals(1, indexOfJames);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACustomer_whenNotFoundUsingIndexOf_thenReturnMinus1() {
|
||||
Customer john = new Customer(5, "John");
|
||||
int indexOfJohn = findACustomerInGivenList.findUsingIndexOf(john, customers);
|
||||
|
||||
assertEquals(-1, indexOfJohn);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameFoundUsingIterator_thenReturnCustomer() {
|
||||
Customer james = findACustomerInGivenList.findUsingIterator("James", customers);
|
||||
|
||||
assertEquals("James", james.getName());
|
||||
assertEquals(2, james.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameNotFoundUsingIterator_thenReturnNull() {
|
||||
Customer john = findACustomerInGivenList.findUsingIterator("John", customers);
|
||||
|
||||
assertNull(john);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameFoundUsingEnhancedFor_thenReturnCustomer() {
|
||||
Customer james = findACustomerInGivenList.findUsingEnhancedForLoop("James", customers);
|
||||
|
||||
assertEquals("James", james.getName());
|
||||
assertEquals(2, james.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameNotFoundUsingEnhancedFor_thenReturnNull() {
|
||||
Customer john = findACustomerInGivenList.findUsingEnhancedForLoop("John", customers);
|
||||
|
||||
assertNull(john);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameFoundUsingStream_thenReturnCustomer() {
|
||||
Customer james = findACustomerInGivenList.findUsingStream("James", customers);
|
||||
|
||||
assertEquals("James", james.getName());
|
||||
assertEquals(2, james.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameNotFoundUsingStream_thenReturnNull() {
|
||||
Customer john = findACustomerInGivenList.findUsingStream("John", customers);
|
||||
|
||||
assertNull(john);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameFoundUsingParallelStream_thenReturnCustomer() {
|
||||
Customer james = findACustomerInGivenList.findUsingParallelStream("James", customers);
|
||||
|
||||
assertEquals("James", james.getName());
|
||||
assertEquals(2, james.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameNotFoundUsingParallelStream_thenReturnNull() {
|
||||
Customer john = findACustomerInGivenList.findUsingParallelStream("John", customers);
|
||||
|
||||
assertNull(john);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameFoundUsingApacheCommon_thenReturnCustomer() {
|
||||
Customer james = findACustomerInGivenList.findUsingApacheCommon("James", customers);
|
||||
|
||||
assertEquals("James", james.getName());
|
||||
assertEquals(2, james.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameNotFoundUsingApacheCommon_thenReturnNull() {
|
||||
Customer john = findACustomerInGivenList.findUsingApacheCommon("John", customers);
|
||||
|
||||
assertNull(john);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameFoundUsingGuava_thenReturnCustomer() {
|
||||
Customer james = findACustomerInGivenList.findUsingGuava("James", customers);
|
||||
|
||||
assertEquals("James", james.getName());
|
||||
assertEquals(2, james.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameNotFoundUsingGuava_thenReturnNull() {
|
||||
Customer john = findACustomerInGivenList.findUsingGuava("John", customers);
|
||||
|
||||
assertNull(john);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,296 @@
|
|||
package com.ossez.java.list;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CustomListUnitTest {
|
||||
@Test
|
||||
public void givenEmptyList_whenIsEmpty_thenTrueIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
|
||||
assertTrue(list.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonEmptyList_whenIsEmpty_thenFalseIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add(null);
|
||||
|
||||
assertFalse(list.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenSize_thenOneIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add(null);
|
||||
|
||||
assertEquals(1, list.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenGet_thenThatElementIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
Object element = list.get(0);
|
||||
|
||||
assertEquals("baeldung", element);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenElementIsAdded_thenGetReturnsThatElement() {
|
||||
List<Object> list = new CustomList<>();
|
||||
boolean succeeded = list.add(null);
|
||||
|
||||
assertTrue(succeeded);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenAnotherIsAdded_thenGetReturnsBoth() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.add(".com");
|
||||
Object element1 = list.get(0);
|
||||
Object element2 = list.get(1);
|
||||
|
||||
assertEquals("baeldung", element1);
|
||||
assertEquals(".com", element2);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenAddToSpecifiedIndex_thenExceptionIsThrown() {
|
||||
new CustomList<>().add(0, null);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenAddAllToTheEnd_thenExceptionIsThrown() {
|
||||
Collection<Object> collection = new ArrayList<>();
|
||||
List<Object> list = new CustomList<>();
|
||||
list.addAll(collection);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenAddAllToSpecifiedIndex_thenExceptionIsThrown() {
|
||||
Collection<Object> collection = new ArrayList<>();
|
||||
List<Object> list = new CustomList<>();
|
||||
list.addAll(0, collection);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenRemoveAtSpecifiedIndex_thenExceptionIsThrown() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.remove(0);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenRemoveSpecifiedElement_thenExceptionIsThrown() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.remove("baeldung");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenRemoveAll_thenExceptionIsThrown() {
|
||||
Collection<Object> collection = new ArrayList<>();
|
||||
collection.add("baeldung");
|
||||
List<Object> list = new CustomList<>();
|
||||
list.removeAll(collection);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenRetainAll_thenExceptionIsThrown() {
|
||||
Collection<Object> collection = new ArrayList<>();
|
||||
collection.add("baeldung");
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.retainAll(collection);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenContains_thenFalseIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
|
||||
assertFalse(list.contains(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenContains_thenTrueIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
|
||||
assertTrue(list.contains("baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenContainsAll_thenTrueIsReturned() {
|
||||
Collection<Object> collection = new ArrayList<>();
|
||||
collection.add("baeldung");
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
|
||||
assertTrue(list.containsAll(collection));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenContainsAll_thenEitherTrueOrFalseIsReturned() {
|
||||
Collection<Object> collection1 = new ArrayList<>();
|
||||
collection1.add("baeldung");
|
||||
collection1.add(".com");
|
||||
Collection<Object> collection2 = new ArrayList<>();
|
||||
collection2.add("baeldung");
|
||||
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
|
||||
assertFalse(list.containsAll(collection1));
|
||||
assertTrue(list.containsAll(collection2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenSet_thenOldElementIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
Object element = list.set(0, null);
|
||||
|
||||
assertEquals("baeldung", element);
|
||||
assertNull(list.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenClear_thenAllElementsAreRemoved() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.clear();
|
||||
|
||||
assertTrue(list.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenIndexOf_thenIndexZeroIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
|
||||
assertEquals(0, list.indexOf("baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenIndexOf_thenPositiveIndexOrMinusOneIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.add(".com");
|
||||
list.add(".com");
|
||||
|
||||
assertEquals(1, list.indexOf(".com"));
|
||||
assertEquals(-1, list.indexOf("com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLastIndexOf_thenIndexZeroIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
|
||||
assertEquals(0, list.lastIndexOf("baeldung"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenLastIndexOf_thenPositiveIndexOrMinusOneIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.add("baeldung");
|
||||
list.add(".com");
|
||||
|
||||
assertEquals(1, list.lastIndexOf("baeldung"));
|
||||
assertEquals(-1, list.indexOf("com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSubListZeroToOne_thenListContainingFirstElementIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
List<Object> subList = list.subList(0, 1);
|
||||
|
||||
assertEquals("baeldung", subList.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSubListOneToTwo_thenListContainingSecondElementIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.add(".");
|
||||
list.add("com");
|
||||
List<Object> subList = list.subList(1, 2);
|
||||
|
||||
assertEquals(1, subList.size());
|
||||
assertEquals(".", subList.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithElements_whenToArray_thenArrayContainsThose() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.add(".com");
|
||||
Object[] array = list.toArray();
|
||||
|
||||
assertArrayEquals(new Object[] { "baeldung", ".com" }, array);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenToArray_thenInputArrayIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
String[] input = new String[1];
|
||||
String[] output = list.toArray(input);
|
||||
|
||||
assertArrayEquals(new String[] { "baeldung" }, input);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenToArrayIsCalledWithEmptyInputArray_thenNewArrayIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
String[] input = {};
|
||||
String[] output = list.toArray(input);
|
||||
|
||||
assertArrayEquals(new String[] { "baeldung" }, output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenToArrayIsCalledWithLargerInput_thenOutputHasTrailingNull() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
String[] input = new String[2];
|
||||
String[] output = list.toArray(input);
|
||||
|
||||
assertArrayEquals(new String[] { "baeldung", null }, output);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithOneElement_whenIterator_thenThisElementIsNext() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
Iterator<Object> iterator = list.iterator();
|
||||
|
||||
assertTrue(iterator.hasNext());
|
||||
assertEquals("baeldung", iterator.next());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIteratorHasNextIsCalledTwice_thenTheSecondReturnsFalse() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
Iterator<Object> iterator = list.iterator();
|
||||
|
||||
iterator.next();
|
||||
assertFalse(iterator.hasNext());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
package com.ossez.java.list;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
|
||||
import org.apache.commons.collections4.iterators.ReverseListIterator;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class ReverseIteratorUnitTest {
|
||||
|
||||
private final ReverseIterator reverseIterator = new ReverseIterator();
|
||||
|
||||
private List<String> list;
|
||||
|
||||
private final String originalString = "ABCDE";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
|
||||
list = Lists.newArrayList("A", "B", "C", "D", "E");
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIteratingUsingForLoop_thenCorrect() {
|
||||
|
||||
String reverseString = "";
|
||||
for (int i = list.size(); i-- > 0; ) {
|
||||
reverseString += list.get(i);
|
||||
}
|
||||
assertEquals(reverseString, StringUtils.reverse(originalString));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIteratingUsingListIterator_thenCorrect() {
|
||||
|
||||
String reverseString = "";
|
||||
final ListIterator listIterator = list.listIterator(list.size());
|
||||
while (listIterator.hasPrevious()) {
|
||||
reverseString += listIterator.previous();
|
||||
}
|
||||
assertEquals(reverseString, StringUtils.reverse(originalString));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIteratingUsingCollections_thenCorrect() {
|
||||
|
||||
String reverseString = "";
|
||||
Collections.reverse(list);
|
||||
for (final String item : list) {
|
||||
reverseString += item;
|
||||
}
|
||||
assertEquals(reverseString, StringUtils.reverse(originalString));
|
||||
|
||||
assertEquals("E", list.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIteratingUsingApacheReverseListIterator_thenCorrect() {
|
||||
|
||||
String reverseString = "";
|
||||
final ReverseListIterator listIterator = new ReverseListIterator(list);
|
||||
while (listIterator.hasNext()) {
|
||||
reverseString += listIterator.next();
|
||||
}
|
||||
assertEquals(reverseString, StringUtils.reverse(originalString));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIteratingUsingGuava_thenCorrect() {
|
||||
|
||||
String reverseString = "";
|
||||
final List<String> reversedList = Lists.reverse(list);
|
||||
for (final String item : reversedList) {
|
||||
reverseString += item;
|
||||
}
|
||||
assertEquals(reverseString, StringUtils.reverse(originalString));
|
||||
|
||||
assertEquals("A", list.get(0));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package com.ossez.java8;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class Java8CollectionCleanupUnitTest {
|
||||
|
||||
// tests -
|
||||
|
||||
@Test
|
||||
public void givenListContainsNulls_whenFilteringParallel_thenCorrect() {
|
||||
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
|
||||
final List<Integer> listWithoutNulls = list.parallelStream().filter(Objects::nonNull).collect(Collectors.toList());
|
||||
|
||||
assertThat(listWithoutNulls, hasSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsNulls_whenFilteringSerial_thenCorrect() {
|
||||
final List<Integer> list = Lists.newArrayList(null, 1, 2, null, 3, null);
|
||||
final List<Integer> listWithoutNulls = list.stream().filter(Objects::nonNull).collect(Collectors.toList());
|
||||
|
||||
assertThat(listWithoutNulls, hasSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
|
||||
final List<Integer> listWithoutNulls = Lists.newArrayList(null, 1, 2, null, 3, null);
|
||||
listWithoutNulls.removeIf(Objects::isNull);
|
||||
|
||||
assertThat(listWithoutNulls, hasSize(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListContainsDuplicates_whenRemovingDuplicatesWithJava8_thenCorrect() {
|
||||
final List<Integer> listWithDuplicates = Lists.newArrayList(5, 0, 3, 1, 2, 3, 0, 0);
|
||||
final List<Integer> listWithoutDuplicates = listWithDuplicates.stream().distinct().collect(Collectors.toList());
|
||||
|
||||
assertThat(listWithoutDuplicates, hasSize(5));
|
||||
assertThat(listWithoutDuplicates, containsInAnyOrder(5, 0, 3, 1, 2));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
package com.ossez.java8;
|
||||
|
||||
import com.ossez.java_8_features.Car;
|
||||
import com.ossez.java_8_features.Person;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Java8MaxMinUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenListIsOfIntegerThenMaxCanBeDoneUsingIntegerComparator() {
|
||||
//given
|
||||
final List<Integer> listOfIntegers = Arrays.asList(1, 2, 3, 4, 56, 7, 89, 10);
|
||||
final Integer expectedResult = 89;
|
||||
|
||||
//then
|
||||
final Integer max = listOfIntegers
|
||||
.stream()
|
||||
.mapToInt(v -> v)
|
||||
.max().orElseThrow(NoSuchElementException::new);
|
||||
|
||||
assertEquals("Should be 89", expectedResult, max);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListIsOfPersonObjectThenMinCanBeDoneUsingCustomComparatorThroughLambda() {
|
||||
//given
|
||||
final Person alex = new Person("Alex", 23);
|
||||
final Person john = new Person("John", 40);
|
||||
final Person peter = new Person("Peter", 32);
|
||||
final List<Person> people = Arrays.asList(alex, john, peter);
|
||||
|
||||
//then
|
||||
final Person minByAge = people
|
||||
.stream()
|
||||
.min(Comparator.comparing(Person::getAge))
|
||||
.orElseThrow(NoSuchElementException::new);
|
||||
|
||||
assertEquals("Should be Alex", alex, minByAge);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArrayIsOfIntegerThenMinUsesIntegerComparator() {
|
||||
int[] integers = new int[] { 20, 98, 12, 7, 35 };
|
||||
|
||||
int min = Arrays.stream(integers)
|
||||
.min()
|
||||
.getAsInt();
|
||||
|
||||
assertEquals(7, min);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArrayIsOfCustomTypeThenMaxUsesCustomComparator() {
|
||||
final Car porsche = new Car("Porsche 959", 319);
|
||||
final Car ferrari = new Car("Ferrari 288 GTO", 303);
|
||||
final Car bugatti = new Car("Bugatti Veyron 16.4 Super Sport", 415);
|
||||
final Car mcLaren = new Car("McLaren F1", 355);
|
||||
final Car[] fastCars = { porsche, ferrari, bugatti, mcLaren };
|
||||
|
||||
final Car maxBySpeed = Arrays.stream(fastCars)
|
||||
.max(Comparator.comparing(Car::getTopSpeed))
|
||||
.orElseThrow(NoSuchElementException::new);
|
||||
|
||||
assertEquals(bugatti, maxBySpeed);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
package com.ossez.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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package com.ossez.list.listoflist;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class ListOfListsUnitTest {
|
||||
|
||||
private List<List<? extends Stationery>> listOfLists = new ArrayList<>();
|
||||
private List<Pen> penList = new ArrayList<>();
|
||||
private List<Pencil> pencilList = new ArrayList<>();
|
||||
private List<Rubber> rubberList = new ArrayList<>();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Before
|
||||
public void init() {
|
||||
listOfLists.add(penList);
|
||||
listOfLists.add(pencilList);
|
||||
listOfLists.add(rubberList);
|
||||
|
||||
((ArrayList<Pen>) listOfLists.get(0)).add(new Pen("Pen 1"));
|
||||
((ArrayList<Pencil>) listOfLists.get(1)).add(new Pencil("Pencil 1"));
|
||||
((ArrayList<Rubber>) listOfLists.get(2)).add(new Rubber("Rubber 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfLists_thenCheckNames() {
|
||||
assertEquals("Pen 1", ((Pen) listOfLists.get(0).get(0)).getName());
|
||||
assertEquals("Pencil 1", ((Pencil) listOfLists.get(1).get(0)).getName());
|
||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(2).get(0)).getName());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void givenListOfLists_whenRemovingElements_thenCheckNames() {
|
||||
|
||||
((ArrayList<Pencil>) listOfLists.get(1)).remove(0);
|
||||
listOfLists.remove(1);
|
||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(1).get(0)).getName());
|
||||
listOfLists.remove(0);
|
||||
assertEquals("Rubber 1", ((Rubber) listOfLists.get(0).get(0)).getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenThreeList_whenCombineIntoOneList_thenCheckList() {
|
||||
ArrayList<Pen> pens = new ArrayList<>();
|
||||
pens.add(new Pen("Pen 1"));
|
||||
pens.add(new Pen("Pen 2"));
|
||||
ArrayList<Pencil> pencils = new ArrayList<>();
|
||||
pencils.add(new Pencil("Pencil 1"));
|
||||
pencils.add(new Pencil("Pencil 2"));
|
||||
ArrayList<Rubber> rubbers = new ArrayList<>();
|
||||
rubbers.add(new Rubber("Rubber 1"));
|
||||
rubbers.add(new Rubber("Rubber 2"));
|
||||
|
||||
List<ArrayList<? extends Stationery>> list = new ArrayList<ArrayList<? extends Stationery>>();
|
||||
list.add(pens);
|
||||
list.add(pencils);
|
||||
list.add(rubbers);
|
||||
|
||||
assertEquals("Pen 1", ((Pen) list.get(0).get(0)).getName());
|
||||
assertEquals("Pencil 1", ((Pencil) list.get(1).get(0)).getName());
|
||||
assertEquals("Rubber 1", ((Rubber) list.get(2).get(0)).getName());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
package com.ossez.list.random;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
public class RandomListElementUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() {
|
||||
List<Integer> givenList = Lists.newArrayList(1, 2, 3);
|
||||
Random rand = new Random();
|
||||
|
||||
givenList.get(rand.nextInt(givenList.size()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() {
|
||||
List<Integer> givenList = Lists.newArrayList(1, 2, 3);
|
||||
|
||||
givenList.get((int) (Math.random() * givenList.size()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsRepeat() {
|
||||
Random rand = new Random();
|
||||
List<String> givenList = Lists.newArrayList("one", "two", "three", "four");
|
||||
|
||||
int numberOfElements = 2;
|
||||
|
||||
for (int i = 0; i < numberOfElements; i++) {
|
||||
int randomIndex = rand.nextInt(givenList.size());
|
||||
givenList.get(randomIndex);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsNoRepeat() {
|
||||
Random rand = new Random();
|
||||
List<String> givenList = Lists.newArrayList("one", "two", "three", "four");
|
||||
|
||||
int numberOfElements = 2;
|
||||
|
||||
for (int i = 0; i < numberOfElements; i++) {
|
||||
int randomIndex = rand.nextInt(givenList.size());
|
||||
givenList.get(randomIndex);
|
||||
givenList.remove(randomIndex);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenSeriesLengthChosen_shouldReturnRandomSeries() {
|
||||
List<Integer> givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6);
|
||||
Collections.shuffle(givenList);
|
||||
|
||||
int randomSeriesLength = 3;
|
||||
|
||||
givenList.subList(0, randomSeriesLength - 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenRandomIndexChosen_shouldReturnElementThreadSafely() {
|
||||
List<Integer> givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6);
|
||||
int randomIndex = ThreadLocalRandom.current().nextInt(10) % givenList.size();
|
||||
|
||||
givenList.get(randomIndex);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,212 @@
|
|||
package com.ossez.list.removeall;
|
||||
|
||||
import static com.ossez.list.removeall.RemoveAll.removeWithCallingRemoveUntilModifies;
|
||||
import static com.ossez.list.removeall.RemoveAll.removeWithCollectingAndReturningRemainingElements;
|
||||
import static com.ossez.list.removeall.RemoveAll.removeWithCollectingRemainingElementsAndAddingToOriginalList;
|
||||
import static com.ossez.list.removeall.RemoveAll.removeWithForEachLoop;
|
||||
import static com.ossez.list.removeall.RemoveAll.removeWithForLoopDecrementOnRemove;
|
||||
import static com.ossez.list.removeall.RemoveAll.removeWithForLoopIncrementIfRemains;
|
||||
import static com.ossez.list.removeall.RemoveAll.removeWithIterator;
|
||||
import static com.ossez.list.removeall.RemoveAll.removeWithRemoveIf;
|
||||
import static com.ossez.list.removeall.RemoveAll.removeWithStandardForLoopUsingIndex;
|
||||
import static com.ossez.list.removeall.RemoveAll.removeWithStreamFilter;
|
||||
import static com.ossez.list.removeall.RemoveAll.removeWithWhileLoopNonPrimitiveElement;
|
||||
import static com.ossez.list.removeall.RemoveAll.removeWithWhileLoopPrimitiveElement;
|
||||
import static com.ossez.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.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
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));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
## Java Date/time conversion Cookbooks and Examples
|
||||
|
||||
This module contains articles about converting between Java date and time objects.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Converting Between LocalDate and XMLGregorianCalendar](https://www.baeldung.com/java-localdate-to-xmlgregoriancalendar)
|
||||
- [Convert Time to Milliseconds in Java](https://www.baeldung.com/java-time-milliseconds)
|
||||
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
|
||||
- [Convert Between java.time.Instant and java.sql.Timestamp](https://www.baeldung.com/java-time-instant-to-java-sql-timestamp)
|
|
@ -0,0 +1,72 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-datetime-conversion</artifactId>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-datetime-conversion</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.ossez.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.2-SNAPSHOT</version>
|
||||
<relativePath></relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>log4j</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
<version>${log4j.version}</version>
|
||||
</dependency>
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-datetime-conversion</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<maven.compiler.source>1.9</maven.compiler.source>
|
||||
<maven.compiler.target>1.9</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,39 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Class which shows a way to convert java.util.Date into java.time.LocalDate.
|
||||
*
|
||||
* @author abialas
|
||||
*
|
||||
*/
|
||||
public class DateToLocalDateConverter {
|
||||
|
||||
public static LocalDate convertToLocalDateViaInstant(Date dateToConvert) {
|
||||
return dateToConvert.toInstant()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDate();
|
||||
}
|
||||
|
||||
public static LocalDate convertToLocalDateViaSqlDate(Date dateToConvert) {
|
||||
return new java.sql.Date(dateToConvert.getTime()).toLocalDate();
|
||||
}
|
||||
|
||||
public static LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) {
|
||||
return Instant.ofEpochMilli(dateToConvert.getTime())
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDate();
|
||||
}
|
||||
|
||||
public static LocalDate convertToLocalDate(Date dateToConvert) {
|
||||
return LocalDate.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Class which shows a way to convert java.util.Date into java.time.LocalDateTime.
|
||||
*
|
||||
* @author abialas
|
||||
*
|
||||
*/
|
||||
public class DateToLocalDateTimeConverter {
|
||||
|
||||
public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) {
|
||||
return dateToConvert.toInstant()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDateTime();
|
||||
}
|
||||
|
||||
public static LocalDateTime convertToLocalDateTimeViaSqlTimestamp(Date dateToConvert) {
|
||||
return new java.sql.Timestamp(dateToConvert.getTime()).toLocalDateTime();
|
||||
}
|
||||
|
||||
public static LocalDateTime convertToLocalDateTimeViaMilisecond(Date dateToConvert) {
|
||||
return Instant.ofEpochMilli(dateToConvert.getTime())
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDateTime();
|
||||
}
|
||||
|
||||
public static LocalDateTime convertToLocalDateTime(Date dateToConvert) {
|
||||
return LocalDateTime.ofInstant(dateToConvert.toInstant(), ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Class which shows different ways of converting java.time.LocalDateTime into java.util.Date.
|
||||
*
|
||||
* @author abialas
|
||||
*
|
||||
*/
|
||||
public class LocalDateTimeToDateConverter {
|
||||
|
||||
public static Date convertToDateViaSqlTimestamp(LocalDateTime dateToConvert) {
|
||||
return java.sql.Timestamp.valueOf(dateToConvert);
|
||||
}
|
||||
|
||||
public static Date convertToDateViaInstant(LocalDateTime dateToConvert) {
|
||||
return java.util.Date.from(dateToConvert.atZone(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Class which shows different ways of converting java.time.LocalDate into java.util.Date.
|
||||
*
|
||||
* @author abialas
|
||||
*
|
||||
*/
|
||||
public class LocalDateToDateConverter {
|
||||
|
||||
public static Date convertToDateViaSqlDate(LocalDate dateToConvert) {
|
||||
return java.sql.Date.valueOf(dateToConvert);
|
||||
}
|
||||
|
||||
public static Date convertToDateViaInstant(LocalDate dateToConvert) {
|
||||
return java.util.Date.from(dateToConvert.atStartOfDay()
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toInstant());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
package com.baeldung.convert;
|
||||
|
||||
import org.joda.time.Instant;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
public class ConvertDateTimeUnitTest {
|
||||
|
||||
public final long millis = 1556175797428L;
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTime_WhenToEpochMillis_ThenMillis() {
|
||||
ZoneId id = ZoneId.systemDefault();
|
||||
|
||||
LocalDateTime localDateTime =
|
||||
LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(millis), id);
|
||||
|
||||
ZonedDateTime zdt = ZonedDateTime.of(localDateTime, id);
|
||||
|
||||
Assert.assertEquals(millis, zdt.toInstant().toEpochMilli());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJava8Instant_WhenGToEpochMillis_ThenMillis() {
|
||||
java.time.Instant instant = java.time.Instant.ofEpochMilli(millis);
|
||||
Assert.assertEquals(millis, instant.toEpochMilli());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDate_WhenGetTime_ThenMillis() {
|
||||
Date date = new Date(millis);
|
||||
Assert.assertEquals(millis, date.getTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCalendar_WhenGetTimeInMillis_ThenMillis() {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(new Date(millis));
|
||||
Assert.assertEquals(millis, calendar.getTimeInMillis());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJodaInstant_WhenGetMillis_ThenMillis() {
|
||||
Instant jodaInstant = Instant.ofEpochMilli(millis);
|
||||
Assert.assertEquals(millis, jodaInstant.getMillis());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJODADateTime_WhenGetMillis_ThenMillis() {
|
||||
org.joda.time.DateTime jodaDateTime = new org.joda.time.DateTime(millis);
|
||||
Assert.assertEquals(millis, jodaDateTime.getMillis());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.datetime;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import org.joda.time.DateTimeZone;
|
||||
//import org.joda.time.format.ISODateTimeFormat;
|
||||
//import org.joda.time.format.DateTimeFormatter;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.FormatStyle;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ConvertInstantToTimestampUnitTest {
|
||||
|
||||
private final static Logger logger = LoggerFactory.getLogger(ConvertInstantToTimestampUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void givenInstant_whenConvertedToTimestamp_thenGetTimestampWithSamePointOnTimeline() {
|
||||
Instant instant = Instant.now();
|
||||
Timestamp timestamp = Timestamp.from(instant); // same point on the time-line as Instant
|
||||
assertThat(instant.toEpochMilli()).isEqualTo(timestamp.getTime());
|
||||
|
||||
instant = timestamp.toInstant();
|
||||
assertThat(instant.toEpochMilli()).isEqualTo(timestamp.getTime());
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
||||
formatter = formatter.withZone(TimeZone.getTimeZone("UTC").toZoneId());
|
||||
|
||||
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
|
||||
df.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
|
||||
assertThat(formatter.format(instant)).isEqualTo(df.format(timestamp));
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,89 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.temporal.ChronoField;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.datetolocaldate.DateToLocalDateConverter;
|
||||
|
||||
/**
|
||||
* JUnits for {@link DateToLocalDateConverter} class.
|
||||
*
|
||||
* @author abialas
|
||||
*
|
||||
*/
|
||||
public class DateToLocalDateConverterUnitTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010WhenConvertViaInstant() {
|
||||
// given
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(2010, 10, 10);
|
||||
Date dateToConvert = calendar.getTime();
|
||||
|
||||
// when
|
||||
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaInstant(dateToConvert);
|
||||
|
||||
// then
|
||||
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
||||
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
||||
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010WhenConvertViaMiliseconds() {
|
||||
// given
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(2010, 10, 10);
|
||||
Date dateToConvert = calendar.getTime();
|
||||
|
||||
// when
|
||||
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaMilisecond(dateToConvert);
|
||||
|
||||
// then
|
||||
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
||||
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
||||
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010WhenConvertViaSqlDate() {
|
||||
// given
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(2010, 10, 10);
|
||||
Date dateToConvert = calendar.getTime();
|
||||
|
||||
// when
|
||||
LocalDate localDate = DateToLocalDateConverter.convertToLocalDateViaSqlDate(dateToConvert);
|
||||
|
||||
// then
|
||||
assertEquals(2010, localDate.get(ChronoField.YEAR));
|
||||
assertEquals(11, localDate.get(ChronoField.MONTH_OF_YEAR));
|
||||
assertEquals(10, localDate.get(ChronoField.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010WhenConvertToLocalDate() {
|
||||
// given
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(2010, 10, 10);
|
||||
Date dateToConvert = calendar.getTime();
|
||||
|
||||
// when
|
||||
LocalDate localDateTime = DateToLocalDateConverter.convertToLocalDate(dateToConvert);
|
||||
|
||||
// then
|
||||
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
||||
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
||||
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,97 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoField;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.datetolocaldate.DateToLocalDateTimeConverter;
|
||||
|
||||
/**
|
||||
* JUnits for {@link DateToLocalDateTimeConverter} class.
|
||||
*
|
||||
* @author abialas
|
||||
*
|
||||
*/
|
||||
public class DateToLocalDateTimeConverterUnitTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() {
|
||||
// given
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(2010, 10, 10, 8, 20);
|
||||
Date dateToConvert = calendar.getTime();
|
||||
|
||||
// when
|
||||
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaInstant(dateToConvert);
|
||||
|
||||
// then
|
||||
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
||||
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
||||
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
||||
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
||||
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaMiliseconds() {
|
||||
// given
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(2010, 10, 10, 8, 20);
|
||||
Date dateToConvert = calendar.getTime();
|
||||
|
||||
// when
|
||||
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaMilisecond(dateToConvert);
|
||||
|
||||
// then
|
||||
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
||||
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
||||
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
||||
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
||||
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaSqlTimestamp() {
|
||||
// given
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(2010, 10, 10, 8, 20);
|
||||
Date dateToConvert = calendar.getTime();
|
||||
|
||||
// when
|
||||
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTimeViaSqlTimestamp(dateToConvert);
|
||||
|
||||
// then
|
||||
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
||||
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
||||
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
||||
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
||||
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010time8hour20minWhenConvertToLocalDateTime() {
|
||||
// given
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(2010, 10, 10, 8, 20);
|
||||
Date dateToConvert = calendar.getTime();
|
||||
|
||||
// when
|
||||
LocalDateTime localDateTime = DateToLocalDateTimeConverter.convertToLocalDateTime(dateToConvert);
|
||||
|
||||
// then
|
||||
assertEquals(2010, localDateTime.get(ChronoField.YEAR));
|
||||
assertEquals(11, localDateTime.get(ChronoField.MONTH_OF_YEAR));
|
||||
assertEquals(10, localDateTime.get(ChronoField.DAY_OF_MONTH));
|
||||
assertEquals(8, localDateTime.get(ChronoField.HOUR_OF_DAY));
|
||||
assertEquals(20, localDateTime.get(ChronoField.MINUTE_OF_HOUR));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.datetolocaldate.LocalDateTimeToDateConverter;
|
||||
|
||||
/**
|
||||
*
|
||||
* JUnits for {@link LocalDateTimeToDateConverter} class.
|
||||
*
|
||||
* @author abialas
|
||||
*
|
||||
*/
|
||||
public class LocalDateTimeToDateConverterUnitTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010time8hour20minWhenConvertViaInstant() {
|
||||
// given
|
||||
LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20);
|
||||
|
||||
// when
|
||||
Date date = LocalDateTimeToDateConverter.convertToDateViaInstant(dateToConvert);
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
// then
|
||||
assertEquals(2010, calendar.get(Calendar.YEAR));
|
||||
assertEquals(10, calendar.get(Calendar.MONTH));
|
||||
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
assertEquals(8, calendar.get(Calendar.HOUR));
|
||||
assertEquals(20, calendar.get(Calendar.MINUTE));
|
||||
assertEquals(0, calendar.get(Calendar.SECOND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010WhenConvertViaSqlTimestamp() {
|
||||
// given
|
||||
LocalDateTime dateToConvert = LocalDateTime.of(2010, 11, 10, 8, 20);
|
||||
|
||||
// when
|
||||
Date date = LocalDateTimeToDateConverter.convertToDateViaSqlTimestamp(dateToConvert);
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
// then
|
||||
assertEquals(2010, calendar.get(Calendar.YEAR));
|
||||
assertEquals(10, calendar.get(Calendar.MONTH));
|
||||
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
assertEquals(8, calendar.get(Calendar.HOUR));
|
||||
assertEquals(20, calendar.get(Calendar.MINUTE));
|
||||
assertEquals(0, calendar.get(Calendar.SECOND));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.datetolocaldate;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.datetolocaldate.LocalDateToDateConverter;
|
||||
|
||||
/**
|
||||
*
|
||||
* JUnits for {@link LocalDateToDateConverter} class.
|
||||
*
|
||||
* @author abialas
|
||||
*
|
||||
*/
|
||||
public class LocalDateToDateConverterUnitTest {
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010WhenConvertViaInstant() {
|
||||
// given
|
||||
LocalDate dateToConvert = LocalDate.of(2010, 11, 10);
|
||||
|
||||
// when
|
||||
Date date = LocalDateToDateConverter.convertToDateViaInstant(dateToConvert);
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
// then
|
||||
assertEquals(2010, calendar.get(Calendar.YEAR));
|
||||
assertEquals(10, calendar.get(Calendar.MONTH));
|
||||
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shouldReturn10thNovember2010WhenConvertViaSqlDate() {
|
||||
// given
|
||||
LocalDate dateToConvert = LocalDate.of(2010, 11, 10);
|
||||
|
||||
// when
|
||||
Date date = LocalDateToDateConverter.convertToDateViaSqlDate(dateToConvert);
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
// then
|
||||
assertEquals(2010, calendar.get(Calendar.YEAR));
|
||||
assertEquals(10, calendar.get(Calendar.MONTH));
|
||||
assertEquals(10, calendar.get(Calendar.DAY_OF_MONTH));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.xmlgregoriancalendar;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.xml.datatype.DatatypeConfigurationException;
|
||||
import javax.xml.datatype.DatatypeConstants;
|
||||
import javax.xml.datatype.DatatypeFactory;
|
||||
import javax.xml.datatype.XMLGregorianCalendar;
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class XmlGregorianCalendarConverterUnitTest {
|
||||
|
||||
@Test
|
||||
public void fromLocalDateToXMLGregorianCalendar() throws DatatypeConfigurationException {
|
||||
LocalDate localDate = LocalDate.of(2017, 4, 25);
|
||||
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(localDate.toString());
|
||||
|
||||
assertThat(xmlGregorianCalendar.getYear()).isEqualTo(localDate.getYear());
|
||||
assertThat(xmlGregorianCalendar.getMonth()).isEqualTo(localDate.getMonthValue());
|
||||
assertThat(xmlGregorianCalendar.getDay()).isEqualTo(localDate.getDayOfMonth());
|
||||
assertThat(xmlGregorianCalendar.getTimezone()).isEqualTo(DatatypeConstants.FIELD_UNDEFINED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fromXMLGregorianCalendarToLocalDate() throws DatatypeConfigurationException {
|
||||
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-04-25");
|
||||
LocalDate localDate = LocalDate.of(xmlGregorianCalendar.getYear(), xmlGregorianCalendar.getMonth(), xmlGregorianCalendar.getDay());
|
||||
|
||||
assertThat(localDate.getYear()).isEqualTo(xmlGregorianCalendar.getYear());
|
||||
assertThat(localDate.getMonthValue()).isEqualTo(xmlGregorianCalendar.getMonth());
|
||||
assertThat(localDate.getDayOfMonth()).isEqualTo(xmlGregorianCalendar.getDay());
|
||||
}
|
||||
|
||||
}
|
|
@ -1,16 +1,16 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-java-io</artifactId>
|
||||
<version>0.0.1</version>
|
||||
<version>${project.parent.version}</version>
|
||||
<name>core-java-io</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.ossez</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
<groupId>com.ossez.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.2-SNAPSHOT</version>
|
||||
<relativePath></relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -76,7 +76,7 @@
|
|||
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
<version>${slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
|
@ -105,7 +105,8 @@
|
|||
<dependency>
|
||||
<groupId>org.javamoney</groupId>
|
||||
<artifactId>moneta</artifactId>
|
||||
<version>${moneta.version}</version>
|
||||
<version>1.4.2</version>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.owasp.esapi</groupId>
|
||||
|
@ -174,7 +175,7 @@
|
|||
<dependency>
|
||||
<groupId>com.nimbusds</groupId>
|
||||
<artifactId>nimbus-jose-jwt</artifactId>
|
||||
<version>9.0.1</version>
|
||||
<version>${nimbus-jose-jwt.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -198,7 +199,7 @@
|
|||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<classpath/>
|
||||
<argument>com.ossez.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
|
@ -212,7 +213,7 @@
|
|||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
|
||||
<plugin>
|
||||
<!-- Build an executable JAR -->
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
|
@ -252,7 +253,7 @@
|
|||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath />
|
||||
<classpath/>
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
|
@ -286,7 +287,7 @@
|
|||
<avaitility.version>1.7.0</avaitility.version>
|
||||
|
||||
<!-- maven plugins -->
|
||||
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
|
||||
<maven-javadoc-plugin.version>3.3.1</maven-javadoc-plugin.version>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<esapi.version>2.1.0.1</esapi.version>
|
||||
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
|
||||
|
@ -296,6 +297,7 @@
|
|||
<jmime-magic.version>0.1.5</jmime-magic.version>
|
||||
<maven-jar-plugin.version>3.1.0</maven-jar-plugin.version>
|
||||
|
||||
<nimbus-jose-jwt.version>9.13</nimbus-jose-jwt.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,24 +1,42 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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.ossez.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<name>core-java-modules</name>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.ossez</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<version>0.0.2-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>pre-jpms</module>
|
||||
<module>core-java-optional</module>
|
||||
<module>core-java-lang-operators</module>
|
||||
<module>core-java-networking-2</module>
|
||||
<module>core-java-security-manager</module>
|
||||
<module>core-java-8</module>
|
||||
<module>core-java-annotations</module>
|
||||
<module>core-java-collections-list</module>
|
||||
<module>core-java-datetime-conversion</module>
|
||||
<module>core-java-io</module>
|
||||
</modules>
|
||||
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
## Jackson Annotations
|
||||
|
||||
This module contains articles about Jackson annotations.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Guide to @JsonFormat in Jackson](https://www.baeldung.com/jackson-jsonformat)
|
||||
- [More Jackson Annotations](https://www.baeldung.com/jackson-advanced-annotations)
|
||||
- [Jackson – Bidirectional Relationships](https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion)
|
||||
- [Jackson JSON Views](https://www.baeldung.com/jackson-json-view-annotation)
|
|
@ -0,0 +1,50 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>jackson-annotations</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.ossez</groupId>
|
||||
<artifactId>jackson-modules</artifactId>
|
||||
<version>0.0.2-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.module</groupId>
|
||||
<artifactId>jackson-module-jsonSchema</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.rest-assured</groupId>
|
||||
<artifactId>json-path</artifactId>
|
||||
<version>${rest-assured.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>jackson-annotations</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<rest-assured.version>3.1.1</rest-assured.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue