diff --git a/core-java-modules/core-java-collections-2/README.md b/core-java-modules/core-java-collections-2/README.md new file mode 100644 index 0000000000..e5f6126811 --- /dev/null +++ b/core-java-modules/core-java-collections-2/README.md @@ -0,0 +1,14 @@ +========= + +## Core Java Collections Cookbooks and Examples + +### Relevant Articles: +- [Removing Elements from Java Collections](https://www.baeldung.com/java-collection-remove-elements) +- [How to Filter a Collection in Java](https://www.baeldung.com/java-collection-filtering) +- [Join and Split Arrays and Collections in Java](https://www.baeldung.com/java-join-and-split) +- [Java – Combine Multiple Collections](https://www.baeldung.com/java-combine-multiple-collections) +- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections) +- [Shuffling Collections In Java](https://www.baeldung.com/java-shuffle-collection) +- [Sorting in Java](https://www.baeldung.com/java-sorting) +- [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size) +- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections) diff --git a/core-java-modules/core-java-collections-2/pom.xml b/core-java-modules/core-java-collections-2/pom.xml new file mode 100644 index 0000000000..1ffa59657c --- /dev/null +++ b/core-java-modules/core-java-collections-2/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + core-java-collections-2 + core-java-collections-2 + jar + + + com.ossez.core-java-modules + core-java-modules + 0.0.2-SNAPSHOT + ../pom.xml + + + + + org.eclipse.collections + eclipse-collections + ${eclipse.collections.version} + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.apache.commons + commons-exec + ${commons-exec.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.junit.platform + junit-platform-runner + ${junit-platform.version} + test + + + + + 7.1.0 + 1.3 + + + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/combiningcollections/CombiningArrays.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/combiningcollections/CombiningArrays.java new file mode 100644 index 0000000000..0bd194a78c --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/combiningcollections/CombiningArrays.java @@ -0,0 +1,39 @@ +package com.ossez.collections.combiningcollections; + +import java.util.Arrays; +import java.util.stream.Stream; + +import org.apache.commons.lang3.ArrayUtils; + +import com.google.common.collect.ObjectArrays; + +public class CombiningArrays { + + public static Object[] usingNativeJava(Object[] first, Object[] second) { + Object[] combined = new Object[first.length + second.length]; + System.arraycopy(first, 0, combined, 0, first.length); + System.arraycopy(second, 0, combined, first.length, second.length); + return combined; + } + + public static Object[] usingJava8ObjectStream(Object[] first, Object[] second) { + Object[] combined = Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray(); + return combined; + } + + public static Object[] usingJava8FlatMaps(Object[] first, Object[] second) { + Object[] combined = Stream.of(first, second).flatMap(Stream::of).toArray(String[]::new); + return combined; + } + + public static Object[] usingApacheCommons(Object[] first, Object[] second) { + Object[] combined = ArrayUtils.addAll(first, second); + return combined; + } + + public static Object[] usingGuava(Object[] first, Object[] second) { + Object [] combined = ObjectArrays.concat(first, second, Object.class); + return combined; + } + +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/combiningcollections/CombiningLists.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/combiningcollections/CombiningLists.java new file mode 100644 index 0000000000..b41a581f38 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/combiningcollections/CombiningLists.java @@ -0,0 +1,46 @@ +package com.ossez.collections.combiningcollections; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.collections4.ListUtils; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +public class CombiningLists { + + public static List usingNativeJava(List first, List second) { + List combined = new ArrayList<>(); + combined.addAll(first); + combined.addAll(second); + return combined; + } + + public static List usingJava8ObjectStream(List first, List second) { + List combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toList()); + return combined; + } + + public static List usingJava8FlatMaps(List first, List second) { + List combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toList()); + return combined; + } + + public static List usingApacheCommons(List first, List second) { + List combined = ListUtils.union(first, second); + return combined; + } + + public static List usingGuava(List first, List second) { + Iterable combinedIterables = Iterables.unmodifiableIterable( + Iterables.concat(first, second)); + + List combined = Lists.newArrayList(combinedIterables); + return combined; + } + +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/combiningcollections/CombiningMaps.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/combiningcollections/CombiningMaps.java new file mode 100644 index 0000000000..17a6b2463b --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/combiningcollections/CombiningMaps.java @@ -0,0 +1,47 @@ +package com.ossez.collections.combiningcollections; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.exec.util.MapUtils; + +import com.google.common.collect.ImmutableMap; + +public class CombiningMaps { + + public static Map usingPlainJava(Map first, Map second) { + Map combined = new HashMap<>(); + combined.putAll(first); + combined.putAll(second); + return combined; + } + + public static Map usingJava8ForEach(Map first, Map second) { + second.forEach((key, value) -> first.merge(key, value, String::concat)); + return first; + } + + public static Map usingJava8FlatMaps(Map first, Map second) { + Map combined = Stream.of(first, second).map(Map::entrySet).flatMap(Collection::stream) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, String::concat)); + return combined; + + } + + public static Map usingApacheCommons(Map first, Map second) { + Map combined = MapUtils.merge(first, second); + return combined; + } + + public static Map usingGuava(Map first, Map second) { + Map combined = ImmutableMap.builder() + .putAll(first) + .putAll(second) + .build(); + return combined; + } + +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/combiningcollections/CombiningSets.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/combiningcollections/CombiningSets.java new file mode 100644 index 0000000000..d0c0c28272 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/combiningcollections/CombiningSets.java @@ -0,0 +1,42 @@ +package com.ossez.collections.combiningcollections; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.commons.collections4.SetUtils; + +import com.google.common.collect.Sets; + +public class CombiningSets { + + public static Set usingNativeJava(Set first, Set second) { + Set combined = new HashSet<>(); + combined.addAll(first); + combined.addAll(second); + return combined; + } + + public static Set usingJava8ObjectStream(Set first, Set second) { + Set combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toSet()); + return combined; + } + + public static Set usingJava8FlatMaps(Set first, Set second) { + Set combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toSet()); + return combined; + } + + public static Set usingApacheCommons(Set first, Set second) { + Set combined = SetUtils.union(first, second); + return combined; + } + + public static Set usingGuava(Set first, Set second) { + Set combined = Sets.union(first, second); + return combined; + } + +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/filtering/CollectionUtilsCollectionFilter.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/filtering/CollectionUtilsCollectionFilter.java new file mode 100644 index 0000000000..a3cac0e560 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/filtering/CollectionUtilsCollectionFilter.java @@ -0,0 +1,16 @@ +package com.ossez.collections.filtering; + +import java.util.Collection; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.Predicate; + +public class CollectionUtilsCollectionFilter { + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate apacheEventNumberPredicate = item -> item % 2 == 0; + + CollectionUtils.filter(baseCollection, apacheEventNumberPredicate); + return baseCollection; + } +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/filtering/EclipseCollectionsCollectionFilter.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/filtering/EclipseCollectionsCollectionFilter.java new file mode 100644 index 0000000000..f1d4a5287d --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/filtering/EclipseCollectionsCollectionFilter.java @@ -0,0 +1,32 @@ +package com.ossez.collections.filtering; + +import java.util.Collection; + +import org.eclipse.collections.api.block.predicate.Predicate; +import org.eclipse.collections.impl.factory.Lists; +import org.eclipse.collections.impl.utility.Iterate; + +public class EclipseCollectionsCollectionFilter { + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate eclipsePredicate = item -> item % 2 == 0; + Collection filteredList = Lists.mutable.ofAll(baseCollection) + .select(eclipsePredicate); + + return filteredList; + } + + static public Collection findEvenNumbersUsingIterate(Collection baseCollection) { + Predicate eclipsePredicate = new Predicate() { + private static final long serialVersionUID = 1L; + + @Override + public boolean accept(Integer arg0) { + return arg0 % 2 == 0; + } + }; + Collection filteredList = Iterate.select(baseCollection, eclipsePredicate); + + return filteredList; + } +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/filtering/GuavaCollectionFilter.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/filtering/GuavaCollectionFilter.java new file mode 100644 index 0000000000..a91c0a5be8 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/filtering/GuavaCollectionFilter.java @@ -0,0 +1,17 @@ +package com.ossez.collections.filtering; + +import java.util.Collection; + +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; + +public class GuavaCollectionFilter { + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate guavaPredicate = item -> item % 2 == 0; + + Collection filteredCollection = Collections2.filter(baseCollection, guavaPredicate); + return filteredCollection; + } + +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/filtering/StreamsCollectionFilter.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/filtering/StreamsCollectionFilter.java new file mode 100644 index 0000000000..d1154f3972 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/filtering/StreamsCollectionFilter.java @@ -0,0 +1,26 @@ +package com.ossez.collections.filtering; + +import java.util.Collection; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +public class StreamsCollectionFilter { + + public static Collection filterCollectionHelperMethod(Collection baseCollection, Predicate predicate) { + return baseCollection.stream() + .filter(predicate) + .collect(Collectors.toList()); + } + + static public Collection findEvenNumbersUsingHelperMethod(Collection baseCollection) { + return filterCollectionHelperMethod(baseCollection, item -> item % 2 == 0); + } + + static public Collection findEvenNumbers(Collection baseCollection) { + Predicate streamsPredicate = item -> item % 2 == 0; + + return baseCollection.stream() + .filter(streamsPredicate) + .collect(Collectors.toList()); + } +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/iterablesize/IterableSize.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/iterablesize/IterableSize.java new file mode 100644 index 0000000000..5d3c6cb70d --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/iterablesize/IterableSize.java @@ -0,0 +1,65 @@ +package com.ossez.collections.iterablesize; + +import java.util.Collection; +import java.util.stream.StreamSupport; + +import org.apache.commons.collections4.IterableUtils; + +import com.google.common.collect.Iterables; + +/** + * Provides methods for getting the size of an {@link Iterable} object. + */ +public class IterableSize { + + /** + * Get the size of {@code Iterable} using Java 7. + * + * @param data the iterable + * @return the size of the iterable + */ + public static int sizeUsingJava7(final Iterable data) { + + if (data instanceof Collection) { + return ((Collection) data).size(); + } + int counter = 0; + for (final Object i : data) { + counter++; + } + return counter; + } + + /** + * Get the size of {@code Iterable} using Java 8. + * + * @param data the iterable + * @return the size of the iterable + */ + public static long sizeUsingJava8(final Iterable data) { + + return StreamSupport.stream(data.spliterator(), false).count(); + } + + /** + * Get the size of {@code Iterable} using Apache Collections. + * + * @param data the iterable + * @return the size of the iterable + */ + public static int sizeUsingApacheCollections(final Iterable data) { + + return IterableUtils.size(data); + } + + /** + * Get the size of {@code Iterable} using Google Guava. + * + * @param data the iterable + * @return the size of the iterable + */ + public static int sizeUsingGoogleGuava(final Iterable data) { + + return Iterables.size(data); + } +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java new file mode 100644 index 0000000000..b83d2be2a9 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java @@ -0,0 +1,19 @@ +package com.ossez.collections.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 collectionAsStream(Collection collection) { + return emptyIfNull(collection).stream(); + } +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java new file mode 100644 index 0000000000..36fdc17464 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java @@ -0,0 +1,21 @@ +package com.ossez.collections.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 collectionAsStream(Collection collection) { + return Optional.ofNullable(collection) + .map(Collection::stream) + .orElseGet(Stream::empty); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java new file mode 100644 index 0000000000..9e798c5ad8 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java @@ -0,0 +1,19 @@ +package com.ossez.collections.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 collectionAsStream(Collection collection) { + return collection == null ? Stream.empty() : collection.stream(); + } + +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/removal/CollectionRemoveIf.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/removal/CollectionRemoveIf.java new file mode 100644 index 0000000000..09636698f2 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/removal/CollectionRemoveIf.java @@ -0,0 +1,19 @@ +package com.ossez.collections.removal; + +import java.util.ArrayList; +import java.util.Collection; + +public class CollectionRemoveIf { + + public static void main(String args[]) { + Collection names = new ArrayList<>(); + names.add("John"); + names.add("Ana"); + names.add("Mary"); + names.add("Anthony"); + names.add("Mark"); + + names.removeIf(e -> e.startsWith("A")); + System.out.println(String.join(",", names)); + } +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/removal/Iterators.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/removal/Iterators.java new file mode 100644 index 0000000000..61a736d6b8 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/removal/Iterators.java @@ -0,0 +1,28 @@ +package com.ossez.collections.removal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +public class Iterators { + + public static void main(String args[]) { + Collection names = new ArrayList<>(); + names.add("John"); + names.add("Ana"); + names.add("Mary"); + names.add("Anthony"); + names.add("Mark"); + + Iterator i = names.iterator(); + + while (i.hasNext()) { + String e = i.next(); + if (e.startsWith("A")) { + i.remove(); + } + } + + System.out.println(String.join(",", names)); + } +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/removal/StreamFilterAndCollector.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/removal/StreamFilterAndCollector.java new file mode 100644 index 0000000000..1850e10b0b --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/removal/StreamFilterAndCollector.java @@ -0,0 +1,23 @@ +package com.ossez.collections.removal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.stream.Collectors; + +public class StreamFilterAndCollector { + + public static void main(String args[]) { + Collection names = new ArrayList<>(); + names.add("John"); + names.add("Ana"); + names.add("Mary"); + names.add("Anthony"); + names.add("Mark"); + + Collection filteredCollection = names + .stream() + .filter(e -> !e.startsWith("A")) + .collect(Collectors.toList()); + System.out.println(String.join(",", filteredCollection)); + } +} diff --git a/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/removal/StreamPartitioningBy.java b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/removal/StreamPartitioningBy.java new file mode 100644 index 0000000000..0daecd6880 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/main/java/com/ossez/collections/removal/StreamPartitioningBy.java @@ -0,0 +1,28 @@ +package com.ossez.collections.removal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class StreamPartitioningBy { + + public static void main(String args[]) { + Collection names = new ArrayList<>(); + names.add("John"); + names.add("Ana"); + names.add("Mary"); + names.add("Anthony"); + names.add("Mark"); + + Map> classifiedElements = names + .stream() + .collect(Collectors.partitioningBy((String e) -> !e.startsWith("A"))); + + String matching = String.join(",", classifiedElements.get(Boolean.TRUE)); + String nonMatching = String.join(",", classifiedElements.get(Boolean.FALSE)); + System.out.println("Matching elements: " + matching); + System.out.println("Non matching elements: " + nonMatching); + } +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/combiningcollections/CombiningArraysUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/combiningcollections/CombiningArraysUnitTest.java new file mode 100644 index 0000000000..c5b59256a0 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/combiningcollections/CombiningArraysUnitTest.java @@ -0,0 +1,53 @@ +package com.ossez.collections.combiningcollections; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class CombiningArraysUnitTest { + private static final String first[] = { + "One", + "Two", + "Three" + }; + + private static final String second[] = { + "Four", + "Five", + "Six" + }; + + private static final String expected[] = { + "One", + "Two", + "Three", + "Four", + "Five", + "Six" + }; + + @Test + public void givenTwoArrays_whenUsingNativeJava_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingNativeJava(first, second)); + } + + @Test + public void givenTwoArrays_whenUsingObjectStreams_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingJava8ObjectStream(first, second)); + } + + @Test + public void givenTwoArrays_whenUsingFlatMaps_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingJava8FlatMaps(first, second)); + } + + @Test + public void givenTwoArrays_whenUsingApacheCommons_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingApacheCommons(first, second)); + } + + @Test + public void givenTwoArrays_whenUsingGuava_thenArraysCombined() { + assertArrayEquals(expected, CombiningArrays.usingGuava(first, second)); + } +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/combiningcollections/CombiningListsUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/combiningcollections/CombiningListsUnitTest.java new file mode 100644 index 0000000000..9e2c258ce8 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/combiningcollections/CombiningListsUnitTest.java @@ -0,0 +1,57 @@ +package com.ossez.collections.combiningcollections; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +public class CombiningListsUnitTest { + private static final List first = Arrays.asList(new Object[]{ + "One", + "Two", + "Three" + }); + + private static final List second = Arrays.asList(new Object[]{ + "Four", + "Five", + "Six" + }); + + private static final List expected = Arrays.asList(new Object[]{ + "One", + "Two", + "Three", + "Four", + "Five", + "Six" + }); + + @Test + public void givenTwoLists_whenUsingNativeJava_thenArraysCombined() { + assertThat(CombiningLists.usingNativeJava(first, second), is(expected)); + } + + @Test + public void givenTwoLists_whenUsingObjectStreams_thenArraysCombined() { + assertThat(CombiningLists.usingJava8ObjectStream(first, second), is(expected)); + } + + @Test + public void givenTwoLists_whenUsingFlatMaps_thenArraysCombined() { + assertThat(CombiningLists.usingJava8FlatMaps(first, second), is(expected)); + } + + @Test + public void givenTwoLists_whenUsingApacheCommons_thenArraysCombined() { + assertThat(CombiningLists.usingApacheCommons(first, second), is(expected)); + } + + @Test + public void givenTwoLists_whenUsingGuava_thenArraysCombined() { + assertThat(CombiningLists.usingGuava(first, second), is(expected)); + } +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/combiningcollections/CombiningMapsUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/combiningcollections/CombiningMapsUnitTest.java new file mode 100644 index 0000000000..8a644c8be1 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/combiningcollections/CombiningMapsUnitTest.java @@ -0,0 +1,54 @@ +package com.ossez.collections.combiningcollections; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +public class CombiningMapsUnitTest { + private static final Map first = new HashMap<>(); + private static final Map second = new HashMap<>(); + private static Map expected = new HashMap<>(); + + static { + first.put("one", "first String"); + first.put("two", "second String"); + + second.put("three", "third String"); + second.put("four", "fourth String"); + + expected.put("one", "first String"); + expected.put("two", "second String"); + expected.put("three", "third String"); + expected.put("four", "fourth String"); + } + + @Test + public void givenTwoMaps_whenUsingNativeJava_thenMapsCombined() { + assertThat(CombiningMaps.usingPlainJava(first, second), is(expected)); + } + + + @Test + public void givenTwoMaps_whenUsingForEach_thenMapsCombined() { + assertThat(CombiningMaps.usingJava8ForEach(first, second), is(expected)); + } + + @Test + public void givenTwoMaps_whenUsingFlatMaps_thenMapsCombined() { + assertThat(CombiningMaps.usingJava8FlatMaps(first, second), is(expected)); + } + + @Test + public void givenTwoMaps_whenUsingApacheCommons_thenMapsCombined() { + assertThat(CombiningMaps.usingApacheCommons(first, second), is(expected)); + } + + @Test + public void givenTwoMaps_whenUsingGuava_thenMapsCombined() { + assertThat(CombiningMaps.usingGuava(first, second), is(expected)); + } +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/combiningcollections/CombiningSetsUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/combiningcollections/CombiningSetsUnitTest.java new file mode 100644 index 0000000000..a75c97b341 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/combiningcollections/CombiningSetsUnitTest.java @@ -0,0 +1,45 @@ + +package com.ossez.collections.combiningcollections; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import org.junit.Test; + +public class CombiningSetsUnitTest { + private static final Set first = new HashSet(Arrays.asList(new Object[] { "One", "Two", "Three" })); + + private static final Set second = new HashSet(Arrays.asList(new Object[] { "Four", "Five", "Six" })); + + private static final Set expected = new HashSet(Arrays + .asList(new Object[] { "One", "Two", "Three", "Four", "Five", "Six" })); + + @Test + public void givenTwoSets_whenUsingNativeJava_thenArraysCombined() { + assertThat(CombiningSets.usingNativeJava(first, second), is(expected)); + } + + @Test + public void givenTwoSets_whenUsingObjectStreams_thenArraysCombined() { + assertThat(CombiningSets.usingJava8ObjectStream(first, second), is(expected)); + } + + @Test + public void givenTwoSets_whenUsingFlatMaps_thenArraysCombined() { + assertThat(CombiningSets.usingJava8FlatMaps(first, second), is(expected)); + } + + @Test + public void givenTwoSets_whenUsingApacheCommons_thenArraysCombined() { + assertThat(CombiningSets.usingApacheCommons(first, second), is(expected)); + } + + @Test + public void givenTwoSets_whenUsingGuava_thenArraysCombined() { + assertThat(CombiningSets.usingGuava(first, second), is(expected)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/filtering/CollectionFiltersUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/filtering/CollectionFiltersUnitTest.java new file mode 100644 index 0000000000..1bf0785342 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/filtering/CollectionFiltersUnitTest.java @@ -0,0 +1,44 @@ +package com.ossez.collections.filtering; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +import org.junit.jupiter.api.Test; +import org.junit.platform.runner.JUnitPlatform; +import org.junit.runner.RunWith; + +@RunWith(JUnitPlatform.class) +public class CollectionFiltersUnitTest { + + private static final Collection BASE_INTEGER_COLLECTION = Arrays.asList(9, 14, 2, 7, 1, 5, 8); + private static final Collection EXPECTED_EVEN_FILTERED_COLLECTION = Arrays.asList(14, 2, 8); + + @Test + public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() { + final Collection baseStrings = Arrays.asList("java", "baeldung", "type", "example", "other"); + + Collection filtered = StreamsCollectionFilter.filterCollectionHelperMethod(baseStrings, item -> item.length() == 4); + + assertThat(filtered).containsExactlyInAnyOrder("java", "type"); + } + + @Test + public void givenAnIntegerCollection_whenFilteringEvenValues_thenObtainTheFilteredCollectionForAllCases() { + Collection filteredWithStreams1 = StreamsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); + Collection filteredWithCollectionUtils = CollectionUtilsCollectionFilter.findEvenNumbers(new ArrayList<>(BASE_INTEGER_COLLECTION)); + Collection filteredWithEclipseCollections = EclipseCollectionsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); + Collection filteredWithEclipseCollectionsUsingIterate = EclipseCollectionsCollectionFilter.findEvenNumbersUsingIterate(BASE_INTEGER_COLLECTION); + Collection filteredWithGuava = GuavaCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION); + + assertThat(filteredWithStreams1).hasSameElementsAs(filteredWithCollectionUtils) + .hasSameElementsAs(filteredWithEclipseCollections) + .hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate) + .hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate) + .hasSameElementsAs(filteredWithGuava) + .hasSameElementsAs(EXPECTED_EVEN_FILTERED_COLLECTION); + } + +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/iterablesize/IterableSizeUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/iterablesize/IterableSizeUnitTest.java new file mode 100644 index 0000000000..93f30d71a2 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/iterablesize/IterableSizeUnitTest.java @@ -0,0 +1,59 @@ +package com.ossez.collections.iterablesize; + +import static org.junit.Assert.assertEquals; + +import java.sql.SQLException; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.google.common.collect.Lists; + +class IterableSizeUnitTest { + + private final List list = Lists.newArrayList("Apple", "Orange", "Banana"); + + private Iterable data; + + @Test + void whenUsingJava7_iterableOfCollectionType_thenCorrectSize() { + + final int size = IterableSize.sizeUsingJava7(list); + + assertEquals(3, size); + } + + @Test + void whenUsingJava7_iterableNotOfCollectionType_thenCorrect() { + + final SQLException exception = new SQLException(); + exception.setNextException(new SQLException()); + final int size = IterableSize.sizeUsingJava7(exception); + + assertEquals(2, size); + } + + @Test + void whenUsingJava8_thenCorrect() { + + final long size = IterableSize.sizeUsingJava8(list); + + assertEquals(3, size); + } + + @Test + void whenUsingApacheCollections_thenCorrect() { + + final int size = IterableSize.sizeUsingApacheCollections(list); + + assertEquals(3, size); + } + + @Test + void whenUsingGoogleGuava_thenCorrect() { + + final int size = IterableSize.sizeUsingGoogleGuava(list); + + assertEquals(3, size); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/joinsplit/CollectionsJoinAndSplitJUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/joinsplit/CollectionsJoinAndSplitJUnitTest.java new file mode 100644 index 0000000000..0afbe89978 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/joinsplit/CollectionsJoinAndSplitJUnitTest.java @@ -0,0 +1,62 @@ +package com.ossez.collections.joinsplit; + +import java.util.ArrayList; +import java.util.Collections; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class CollectionsJoinAndSplitJUnitTest { + + private ArrayList sauces = new ArrayList<>(); + private ArrayList cheeses = new ArrayList<>(); + private ArrayList vegetables = new ArrayList<>(); + + private ArrayList> ingredients = new ArrayList<>(); + + @Before + public void init() { + sauces.add("Olive Oil"); + sauces.add("Marinara"); + + cheeses.add("Mozzarella"); + cheeses.add("Feta"); + cheeses.add("Parmesan"); + + vegetables.add("Olives"); + vegetables.add("Spinach"); + vegetables.add("Green Peppers"); + + ingredients.add(sauces); + ingredients.add(cheeses); + ingredients.add(vegetables); + } + + @Test + public void givenThreeArrayLists_whenJoiningIntoOneArrayList_shouldSucceed() { + ArrayList> toppings = new ArrayList<>(); + + toppings.add(sauces); + toppings.add(cheeses); + toppings.add(vegetables); + + Assert.assertTrue(toppings.size() == 3); + Assert.assertTrue(toppings.contains(sauces)); + Assert.assertTrue(toppings.contains(cheeses)); + Assert.assertTrue(toppings.contains(vegetables)); + } + + @Test + public void givenOneArrayList_whenSplittingIntoTwoArrayLists_shouldSucceed() { + + ArrayList> removedToppings = new ArrayList<>(); + removedToppings.add(ingredients.remove(ingredients.indexOf(vegetables))); + + Assert.assertTrue(removedToppings.contains(vegetables)); + Assert.assertTrue(removedToppings.size() == 1); + Assert.assertTrue(ingredients.size() == 2); + Assert.assertTrue(ingredients.contains(sauces)); + Assert.assertTrue(ingredients.contains(cheeses)); + } +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/joinsplit/JoinSplitCollectionsUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/joinsplit/JoinSplitCollectionsUnitTest.java new file mode 100644 index 0000000000..00f652b9a7 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/joinsplit/JoinSplitCollectionsUnitTest.java @@ -0,0 +1,154 @@ +package com.ossez.collections.joinsplit; + +import org.junit.Test; + +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.*; + +public class JoinSplitCollectionsUnitTest { + + @Test + public void whenJoiningTwoArrays_thenJoined() { + String[] animals1 = new String[] { "Dog", "Cat" }; + String[] animals2 = new String[] { "Bird", "Cow" }; + String[] result = Stream.concat(Arrays.stream(animals1), Arrays.stream(animals2)).toArray(String[]::new); + + assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" }); + } + + @Test + public void whenJoiningTwoCollections_thenJoined() { + Collection collection1 = Arrays.asList("Dog", "Cat"); + Collection collection2 = Arrays.asList("Bird", "Cow", "Moose"); + Collection result = Stream.concat(collection1.stream(), collection2.stream()).collect(Collectors.toList()); + + assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow", "Moose"))); + } + + @Test + public void whenJoiningTwoCollectionsWithFilter_thenJoined() { + Collection collection1 = Arrays.asList("Dog", "Cat"); + Collection collection2 = Arrays.asList("Bird", "Cow", "Moose"); + Collection result = Stream.concat(collection1.stream(), collection2.stream()).filter(e -> e.length() == 3).collect(Collectors.toList()); + + assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Cow"))); + } + + @Test + public void whenConvertArrayToString_thenConverted() { + String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow" }; + String result = Arrays.stream(animals).collect(Collectors.joining(", ")); + + assertEquals(result, "Dog, Cat, Bird, Cow"); + } + + @Test + public void whenConvertCollectionToString_thenConverted() { + Collection animals = Arrays.asList("Dog", "Cat", "Bird", "Cow"); + String result = animals.stream().collect(Collectors.joining(", ")); + + assertEquals(result, "Dog, Cat, Bird, Cow"); + } + + @Test + public void whenConvertMapToString_thenConverted() { + Map animals = new HashMap<>(); + animals.put(1, "Dog"); + animals.put(2, "Cat"); + animals.put(3, "Cow"); + + String result = animals.entrySet().stream().map(entry -> entry.getKey() + " = " + entry.getValue()).collect(Collectors.joining(", ")); + + assertEquals(result, "1 = Dog, 2 = Cat, 3 = Cow"); + } + + @Test + public void whenConvertNestedCollectionToString_thenConverted() { + Collection> nested = new ArrayList<>(); + nested.add(Arrays.asList("Dog", "Cat")); + nested.add(Arrays.asList("Cow", "Pig")); + + String result = nested.stream().map(nextList -> nextList.stream().collect(Collectors.joining("-"))).collect(Collectors.joining("; ")); + + assertEquals(result, "Dog-Cat; Cow-Pig"); + } + + @Test + public void whenConvertCollectionToStringAndSkipNull_thenConverted() { + Collection animals = Arrays.asList("Dog", "Cat", null, "Moose"); + String result = animals.stream().filter(Objects::nonNull).collect(Collectors.joining(", ")); + + assertEquals(result, "Dog, Cat, Moose"); + } + + @Test + public void whenSplitCollectionHalf_thenConverted() { + Collection animals = Arrays.asList("Dog", "Cat", "Cow", "Bird", "Moose", "Pig"); + Collection result1 = new ArrayList<>(); + Collection result2 = new ArrayList<>(); + AtomicInteger count = new AtomicInteger(); + int midpoint = Math.round(animals.size() / 2); + + animals.forEach(next -> { + int index = count.getAndIncrement(); + if (index < midpoint) { + result1.add(next); + } else { + result2.add(next); + } + }); + + assertTrue(result1.equals(Arrays.asList("Dog", "Cat", "Cow"))); + assertTrue(result2.equals(Arrays.asList("Bird", "Moose", "Pig"))); + } + + @Test + public void whenSplitArrayByWordLength_thenConverted() { + String[] animals = new String[] { "Dog", "Cat", "Bird", "Cow", "Pig", "Moose" }; + Map> result = Arrays.stream(animals).collect(Collectors.groupingBy(String::length)); + + assertTrue(result.get(3).equals(Arrays.asList("Dog", "Cat", "Cow", "Pig"))); + assertTrue(result.get(4).equals(Arrays.asList("Bird"))); + assertTrue(result.get(5).equals(Arrays.asList("Moose"))); + } + + @Test + public void whenConvertStringToArray_thenConverted() { + String animals = "Dog, Cat, Bird, Cow"; + String[] result = animals.split(", "); + + assertArrayEquals(result, new String[] { "Dog", "Cat", "Bird", "Cow" }); + } + + @Test + public void whenConvertStringToCollection_thenConverted() { + String animals = "Dog, Cat, Bird, Cow"; + Collection result = Arrays.asList(animals.split(", ")); + + assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow"))); + } + + @Test + public void whenConvertStringToMap_thenConverted() { + String animals = "1 = Dog, 2 = Cat, 3 = Bird"; + + Map result = Arrays.stream(animals.split(", ")).map(next -> next.split(" = ")).collect(Collectors.toMap(entry -> Integer.parseInt(entry[0]), entry -> entry[1])); + + assertEquals(result.get(1), "Dog"); + assertEquals(result.get(2), "Cat"); + assertEquals(result.get(3), "Bird"); + } + + @Test + public void whenConvertCollectionToStringMultipleSeparators_thenConverted() { + String animals = "Dog. , Cat, Bird. Cow"; + + Collection result = Arrays.stream(animals.split("[,|.]")).map(String::trim).filter(next -> !next.isEmpty()).collect(Collectors.toList()); + + assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow"))); + } +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/multiplecollections/CombineMultipleCollectionsUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/multiplecollections/CombineMultipleCollectionsUnitTest.java new file mode 100644 index 0000000000..757328f18f --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/multiplecollections/CombineMultipleCollectionsUnitTest.java @@ -0,0 +1,135 @@ +package com.ossez.collections.multiplecollections; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.IterableUtils; +import org.junit.Assert; +import org.junit.Test; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.util.Arrays.asList; + +public class CombineMultipleCollectionsUnitTest { + + @Test + public void givenUsingJava8_whenConcatenatingUsingConcat_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + Collection collectionC = asList("W", "X"); + + Stream combinedStream = Stream.concat(Stream.concat(collectionA.stream(), collectionB.stream()), collectionC.stream()); + Collection collectionCombined = combinedStream.collect(Collectors.toList()); + + Assert.assertEquals(asList("S", "T", "U", "V", "W", "X"), collectionCombined); + } + + @Test + public void givenUsingJava8_whenConcatenatingUsingflatMap_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + + Stream combinedStream = Stream.of(collectionA, collectionB).flatMap(Collection::stream); + Collection collectionCombined = combinedStream.collect(Collectors.toList()); + + Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined); + } + + @Test + public void givenUsingGuava_whenConcatenatingUsingIterables_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + + Iterable combinedIterables = Iterables.unmodifiableIterable(Iterables.concat(collectionA, collectionB)); + Collection collectionCombined = Lists.newArrayList(combinedIterables); + + Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined); + } + + @Test + public void givenUsingJava7_whenConcatenatingUsingIterables_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + + Iterable combinedIterables = concat(collectionA, collectionB); + Collection collectionCombined = makeListFromIterable(combinedIterables); + Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined); + } + + public static Iterable concat(Iterable i1, Iterable i2) { + return new Iterable() { + public Iterator iterator() { + return new Iterator() { + Iterator listIterator = i1.iterator(); + Boolean checkedHasNext; + E nextValue; + private boolean startTheSecond; + + void theNext() { + if (listIterator.hasNext()) { + checkedHasNext = true; + nextValue = listIterator.next(); + } else if (startTheSecond) + checkedHasNext = false; + else { + startTheSecond = true; + listIterator = i2.iterator(); + theNext(); + } + } + + public boolean hasNext() { + if (checkedHasNext == null) + theNext(); + return checkedHasNext; + } + + public E next() { + if (!hasNext()) + throw new NoSuchElementException(); + checkedHasNext = null; + return nextValue; + } + + public void remove() { + listIterator.remove(); + } + }; + } + }; + } + + public static List makeListFromIterable(Iterable iter) { + List list = new ArrayList<>(); + for (E item : iter) { + list.add(item); + } + return list; + } + + @Test + public void givenUsingApacheCommons_whenConcatenatingUsingUnion_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + + Iterable combinedIterables = CollectionUtils.union(collectionA, collectionB); + Collection collectionCombined = Lists.newArrayList(combinedIterables); + + Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined); + } + + @Test + public void givenUsingApacheCommons_whenConcatenatingUsingChainedIterable_thenCorrect() { + Collection collectionA = asList("S", "T"); + Collection collectionB = asList("U", "V"); + + Iterable combinedIterables = IterableUtils.chainedIterable(collectionA, collectionB); + Collection collectionCombined = Lists.newArrayList(combinedIterables); + + Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined); + } +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java new file mode 100644 index 0000000000..e534107721 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java @@ -0,0 +1,38 @@ +package com.ossez.collections.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 collection = null; + Stream expResult = Stream.empty(); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + @Test + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { + Collection collection = Arrays.asList("a", "b", "c"); + Stream expResult = Arrays.stream(new String[] { "a", "b", "c" }); + Stream 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(); + } + +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java new file mode 100644 index 0000000000..af166c31f8 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java @@ -0,0 +1,38 @@ +package com.ossez.collections.nullsafecollectionstreams; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.stream.Stream; + +import org.junit.Test; +import static org.junit.Assert.*; + +public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest { + + private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = + new NullSafeCollectionStreamsUsingJava8OptionalContainer(); + @Test + public void whenCollectionIsNull_thenExpectAnEmptyStream() { + Collection collection = null; + Stream expResult = Stream.empty(); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + @Test + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { + Collection collection = Arrays.asList("a", "b", "c"); + Stream expResult = Arrays.stream(new String[] { "a", "b", "c" }); + Stream 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(); + } + +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java new file mode 100644 index 0000000000..3f42f784a8 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java @@ -0,0 +1,39 @@ +package com.ossez.collections.nullsafecollectionstreams; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.stream.Stream; + +import org.junit.Test; +import static org.junit.Assert.*; + +public class NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest { + + private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance = + new NullSafeCollectionStreamsUsingNullDereferenceCheck(); + + @Test + public void whenCollectionIsNull_thenExpectAnEmptyStream() { + Collection collection = null; + Stream expResult = Stream.empty(); + Stream result = instance.collectionAsStream(collection); + assertStreamEquals(expResult, result); + } + + @Test + public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() { + Collection collection = Arrays.asList("a", "b", "c"); + Stream expResult = Arrays.stream(new String[] { "a", "b", "c" }); + Stream 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(); + } + +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/removal/RemovalUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/removal/RemovalUnitTest.java new file mode 100644 index 0000000000..e4039dad85 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/removal/RemovalUnitTest.java @@ -0,0 +1,77 @@ +package com.ossez.collections.removal; + +import org.junit.Before; +import org.junit.Test; + +import java.util.*; +import java.util.stream.Collectors; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +public class RemovalUnitTest { + + Collection names; + Collection expected; + Collection removed; + + @Before + public void setupTestData() { + names = new ArrayList<>(); + expected = new ArrayList<>(); + removed = new ArrayList<>(); + + names.add("John"); + names.add("Ana"); + names.add("Mary"); + names.add("Anthony"); + names.add("Mark"); + + expected.add("John"); + expected.add("Mary"); + expected.add("Mark"); + + removed.add("Ana"); + removed.add("Anthony"); + } + + @Test + public void givenCollectionOfNames_whenUsingIteratorToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() { + Iterator i = names.iterator(); + + while (i.hasNext()) { + String e = i.next(); + if (e.startsWith("A")) { + i.remove(); + } + } + + assertThat(names, is(expected)); + } + + @Test + public void givenCollectionOfNames_whenUsingRemoveIfToRemoveAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() { + names.removeIf(e -> e.startsWith("A")); + assertThat(names, is(expected)); + } + + @Test + public void givenCollectionOfNames_whenUsingStreamToFilterAllNamesStartingWithLetterA_finalListShouldContainNoNamesStartingWithLetterA() { + Collection filteredCollection = names + .stream() + .filter(e -> !e.startsWith("A")) + .collect(Collectors.toList()); + assertThat(filteredCollection, is(expected)); + } + + @Test + public void givenCollectionOfNames_whenUsingStreamAndPartitioningByToFindNamesThatStartWithLetterA_shouldFind3MatchingAnd2NonMatching() { + Map> classifiedElements = names + .stream() + .collect(Collectors.partitioningBy((String e) -> !e.startsWith("A"))); + + assertThat(classifiedElements.get(Boolean.TRUE), is(expected)); + assertThat(classifiedElements.get(Boolean.FALSE), is(removed)); + } + +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/shufflingcollections/ShufflingCollectionsUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/shufflingcollections/ShufflingCollectionsUnitTest.java new file mode 100644 index 0000000000..ac3766801b --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/shufflingcollections/ShufflingCollectionsUnitTest.java @@ -0,0 +1,70 @@ +package com.ossez.collections.shufflingcollections; + +import org.junit.Test; + +import java.util.*; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ShufflingCollectionsUnitTest { + + @Test + public void whenShufflingList_thenListIsShuffled() { + List students = Arrays.asList("Foo", "Bar", "Baz", "Qux"); + + System.out.println("List before shuffling:"); + System.out.println(students); + + Collections.shuffle(students); + System.out.println("List after shuffling:"); + System.out.println(students); + } + + @Test + public void whenShufflingMapEntries_thenValuesAreShuffled() { + Map studentsById = new HashMap<>(); + studentsById.put(1, "Foo"); + studentsById.put(2, "Bar"); + studentsById.put(3, "Baz"); + studentsById.put(4, "Qux"); + + System.out.println("Students before shuffling:"); + System.out.println(studentsById.values()); + + List> shuffledStudentEntries = new ArrayList<>(studentsById.entrySet()); + Collections.shuffle(shuffledStudentEntries); + + List shuffledStudents = shuffledStudentEntries.stream() + .map(Map.Entry::getValue) + .collect(Collectors.toList()); + + System.out.println("Students after shuffling"); + System.out.println(shuffledStudents); + } + + @Test + public void whenShufflingSet_thenElementsAreShuffled() { + Set students = new HashSet<>(Arrays.asList("Foo", "Bar", "Baz", "Qux")); + + System.out.println("Set before shuffling:"); + System.out.println(students); + + List studentList = new ArrayList<>(students); + + Collections.shuffle(studentList); + System.out.println("Shuffled set elements:"); + System.out.println(studentList); + } + + @Test + public void whenShufflingWithSameRandomness_thenElementsAreShuffledDeterministically() { + List students_1 = Arrays.asList("Foo", "Bar", "Baz", "Qux"); + List students_2 = Arrays.asList("Foo", "Bar", "Baz", "Qux"); + + Collections.shuffle(students_1, new Random(5)); + Collections.shuffle(students_2, new Random(5)); + + assertThat(students_1).isEqualTo(students_2); + } +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/sorting/Employee.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/sorting/Employee.java new file mode 100644 index 0000000000..2007237460 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/sorting/Employee.java @@ -0,0 +1,62 @@ +package com.ossez.collections.sorting; + +public class Employee implements Comparable { + + private String name; + private int age; + private double salary; + + public Employee(String name, int age, double salary) { + this.name = name; + this.age = age; + this.salary = salary; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + + @Override + public boolean equals(Object obj) { + return ((Employee) obj).getName() + .equals(getName()); + } + + @Override + public int compareTo(Object o) { + Employee e = (Employee) o; + return getName().compareTo(e.getName()); + } + + @Override + public String toString() { + return new StringBuffer().append("(") + .append(getName()) + .append(getAge()) + .append(",") + .append(getSalary()) + .append(")") + .toString(); + } + +} diff --git a/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/sorting/JavaSortingUnitTest.java b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/sorting/JavaSortingUnitTest.java new file mode 100644 index 0000000000..b307a13597 --- /dev/null +++ b/core-java-modules/core-java-collections-2/src/test/java/com/ossez/collections/sorting/JavaSortingUnitTest.java @@ -0,0 +1,156 @@ +package com.ossez.collections.sorting; + +import com.google.common.primitives.Ints; +import org.apache.commons.lang3.ArrayUtils; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import static org.junit.Assert.assertTrue; + +public class JavaSortingUnitTest { + + private int[] toSort; + private int[] sortedInts; + private int[] sortedRangeInts; + private Employee[] employees; + private Employee[] employeesSorted; + private Employee[] employeesSortedByAge; + private HashMap map; + + @Before + public void initVariables() { + + toSort = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; + sortedInts = new int[] { 1, 5, 7, 66, 88, 89, 123, 200, 255 }; + sortedRangeInts = new int[] { 5, 1, 89, 7, 88, 200, 255, 123, 66 }; + + employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }; + employeesSorted = new Employee[] { new Employee("Earl", 43, 10000), new Employee("Frank", 33, 70000), new Employee("Jessica", 23, 4000), new Employee("John", 23, 5000), new Employee("Pearl", 33, 4000), new Employee("Steve", 26, 6000) }; + employeesSortedByAge = new Employee[] { new Employee("John", 23, 5000), new Employee("Jessica", 23, 4000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 70000), new Employee("Pearl", 33, 4000), new Employee("Earl", 43, 10000) }; + + map = new HashMap<>(); + map.put(55, "John"); + map.put(22, "Apple"); + map.put(66, "Earl"); + map.put(77, "Pearl"); + map.put(12, "George"); + map.put(6, "Rocky"); + + } + + @Test + public void givenIntArray_whenUsingSort_thenSortedArray() { + Arrays.sort(toSort); + + assertTrue(Arrays.equals(toSort, sortedInts)); + } + + @Test + public void givenIntegerArray_whenUsingSort_thenSortedArray() { + Integer[] integers = ArrayUtils.toObject(toSort); + Arrays.sort(integers, Comparator.comparingInt(a -> a)); + + assertTrue(Arrays.equals(integers, ArrayUtils.toObject(sortedInts))); + } + + @Test + public void givenArray_whenUsingSortWithLambdas_thenSortedArray() { + Integer[] integersToSort = ArrayUtils.toObject(toSort); + Arrays.sort(integersToSort, Comparator.comparingInt(a -> a)); + + assertTrue(Arrays.equals(integersToSort, ArrayUtils.toObject(sortedInts))); + } + + @Test + public void givenEmpArray_SortEmpArray_thenSortedArrayinNaturalOrder() { + Arrays.sort(employees); + + assertTrue(Arrays.equals(employees, employeesSorted)); + } + + @Test + public void givenIntArray_whenUsingRangeSort_thenRangeSortedArray() { + Arrays.sort(toSort, 3, 7); + + assertTrue(Arrays.equals(toSort, sortedRangeInts)); + } + + @Test + public void givenIntArray_whenUsingParallelSort_thenArraySorted() { + Arrays.parallelSort(toSort); + + assertTrue(Arrays.equals(toSort, sortedInts)); + } + + @Test + public void givenArrayObjects_whenUsingComparing_thenSortedArrayObjects() { + List employeesList = Arrays.asList(employees); + + employeesList.sort(Comparator.comparing(Employee::getAge));// .thenComparing(Employee::getName)); + + assertTrue(Arrays.equals(employeesList.toArray(), employeesSortedByAge)); + } + + @Test + public void givenList_whenUsingSort_thenSortedList() { + List toSortList = Ints.asList(toSort); + Collections.sort(toSortList); + + assertTrue(Arrays.equals(toSortList.toArray(), ArrayUtils.toObject(sortedInts))); + } + + @Test + public void givenMap_whenSortingByKeys_thenSortedMap() { + Integer[] sortedKeys = new Integer[] { 6, 12, 22, 55, 66, 77 }; + + List> entries = new ArrayList<>(map.entrySet()); + entries.sort(Comparator.comparing(Entry::getKey)); + HashMap sortedMap = new LinkedHashMap<>(); + for (Map.Entry entry : entries) { + sortedMap.put(entry.getKey(), entry.getValue()); + } + + assertTrue(Arrays.equals(sortedMap.keySet() + .toArray(), sortedKeys)); + } + + @Test + public void givenMap_whenSortingByValues_thenSortedMap() { + String[] sortedValues = new String[] { "Apple", "Earl", "George", "John", "Pearl", "Rocky" }; + + List> entries = new ArrayList<>(map.entrySet()); + entries.sort(Comparator.comparing(Entry::getValue)); + HashMap sortedMap = new LinkedHashMap<>(); + for (Map.Entry entry : entries) { + sortedMap.put(entry.getKey(), entry.getValue()); + } + + assertTrue(Arrays.equals(sortedMap.values() + .toArray(), sortedValues)); + } + + @Test + public void givenSet_whenUsingSort_thenSortedSet() { + HashSet integersSet = new LinkedHashSet<>(Ints.asList(toSort)); + HashSet descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(255, 200, 123, 89, 88, 66, 7, 5, 1)); + + ArrayList list = new ArrayList<>(integersSet); + list.sort(Comparator.reverseOrder()); + integersSet = new LinkedHashSet<>(list); + + assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray())); + } + +}