core-java-collections-2 模块添加到仓库中

This commit is contained in:
YuCheng Hu 2022-05-03 12:00:20 -04:00
parent 0d169bb516
commit fea3e3b8a3
34 changed files with 1695 additions and 0 deletions

View File

@ -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)

View File

@ -0,0 +1,51 @@
<?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-2</artifactId>
<name>core-java-collections-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse.collections.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-exec</artifactId>
<version>${commons-exec.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit-platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<eclipse.collections.version>7.1.0</eclipse.collections.version>
<commons-exec.version>1.3</commons-exec.version>
</properties>
</project>

View File

@ -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;
}
}

View File

@ -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<Object> usingNativeJava(List<Object> first, List<Object> second) {
List<Object> combined = new ArrayList<>();
combined.addAll(first);
combined.addAll(second);
return combined;
}
public static List<Object> usingJava8ObjectStream(List<Object> first, List<Object> second) {
List<Object> combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toList());
return combined;
}
public static List<Object> usingJava8FlatMaps(List<Object> first, List<Object> second) {
List<Object> combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toList());
return combined;
}
public static List<Object> usingApacheCommons(List<Object> first, List<Object> second) {
List<Object> combined = ListUtils.union(first, second);
return combined;
}
public static List<Object> usingGuava(List<Object> first, List<Object> second) {
Iterable<Object> combinedIterables = Iterables.unmodifiableIterable(
Iterables.concat(first, second));
List<Object> combined = Lists.newArrayList(combinedIterables);
return combined;
}
}

View File

@ -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<String, String> usingPlainJava(Map<String, String> first, Map<String, String> second) {
Map<String, String> combined = new HashMap<>();
combined.putAll(first);
combined.putAll(second);
return combined;
}
public static Map<String, String> usingJava8ForEach(Map<String, String> first, Map<String, String> second) {
second.forEach((key, value) -> first.merge(key, value, String::concat));
return first;
}
public static Map<String, String> usingJava8FlatMaps(Map<String, String> first, Map<String, String> second) {
Map<String, String> 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<String, String> usingApacheCommons(Map<String, String> first, Map<String, String> second) {
Map<String, String> combined = MapUtils.merge(first, second);
return combined;
}
public static Map<String, String> usingGuava(Map<String, String> first, Map<String, String> second) {
Map<String, String> combined = ImmutableMap.<String, String>builder()
.putAll(first)
.putAll(second)
.build();
return combined;
}
}

View File

@ -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<Object> usingNativeJava(Set<Object> first, Set<Object> second) {
Set<Object> combined = new HashSet<>();
combined.addAll(first);
combined.addAll(second);
return combined;
}
public static Set<Object> usingJava8ObjectStream(Set<Object> first, Set<Object> second) {
Set<Object> combined = Stream.concat(first.stream(), second.stream()).collect(Collectors.toSet());
return combined;
}
public static Set<Object> usingJava8FlatMaps(Set<Object> first, Set<Object> second) {
Set<Object> combined = Stream.of(first, second).flatMap(Collection::stream).collect(Collectors.toSet());
return combined;
}
public static Set<Object> usingApacheCommons(Set<Object> first, Set<Object> second) {
Set<Object> combined = SetUtils.union(first, second);
return combined;
}
public static Set<Object> usingGuava(Set<Object> first, Set<Object> second) {
Set<Object> combined = Sets.union(first, second);
return combined;
}
}

View File

@ -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<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> apacheEventNumberPredicate = item -> item % 2 == 0;
CollectionUtils.filter(baseCollection, apacheEventNumberPredicate);
return baseCollection;
}
}

View File

@ -0,0 +1,32 @@
package com.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<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> eclipsePredicate = item -> item % 2 == 0;
Collection<Integer> filteredList = Lists.mutable.ofAll(baseCollection)
.select(eclipsePredicate);
return filteredList;
}
static public Collection<Integer> findEvenNumbersUsingIterate(Collection<Integer> baseCollection) {
Predicate<Integer> eclipsePredicate = new Predicate<Integer>() {
private static final long serialVersionUID = 1L;
@Override
public boolean accept(Integer arg0) {
return arg0 % 2 == 0;
}
};
Collection<Integer> filteredList = Iterate.select(baseCollection, eclipsePredicate);
return filteredList;
}
}

View File

@ -0,0 +1,17 @@
package com.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<Integer> findEvenNumbers(Collection<Integer> baseCollection) {
Predicate<Integer> guavaPredicate = item -> item % 2 == 0;
Collection<Integer> filteredCollection = Collections2.filter(baseCollection, guavaPredicate);
return filteredCollection;
}
}

View File

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

View File

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

View File

@ -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<String> collectionAsStream(Collection<String> collection) {
return emptyIfNull(collection).stream();
}
}

View File

@ -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 8s Optional Container
*
* @param collection The collection that is to be converted into a stream
* @return The stream that has been created from the collection or an empty stream if the collection is null
*/
public Stream<String> collectionAsStream(Collection<String> collection) {
return Optional.ofNullable(collection)
.map(Collection::stream)
.orElseGet(Stream::empty);
}
}

View File

@ -0,0 +1,19 @@
package com.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<String> collectionAsStream(Collection<String> collection) {
return collection == null ? Stream.empty() : collection.stream();
}
}

View File

@ -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<String> 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));
}
}

View File

@ -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<String> names = new ArrayList<>();
names.add("John");
names.add("Ana");
names.add("Mary");
names.add("Anthony");
names.add("Mark");
Iterator<String> i = names.iterator();
while (i.hasNext()) {
String e = i.next();
if (e.startsWith("A")) {
i.remove();
}
}
System.out.println(String.join(",", names));
}
}

View File

@ -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<String> names = new ArrayList<>();
names.add("John");
names.add("Ana");
names.add("Mary");
names.add("Anthony");
names.add("Mark");
Collection<String> filteredCollection = names
.stream()
.filter(e -> !e.startsWith("A"))
.collect(Collectors.toList());
System.out.println(String.join(",", filteredCollection));
}
}

View File

@ -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<String> names = new ArrayList<>();
names.add("John");
names.add("Ana");
names.add("Mary");
names.add("Anthony");
names.add("Mark");
Map<Boolean, List<String>> 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);
}
}

View File

@ -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));
}
}

View File

@ -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<Object> first = Arrays.asList(new Object[]{
"One",
"Two",
"Three"
});
private static final List<Object> second = Arrays.asList(new Object[]{
"Four",
"Five",
"Six"
});
private static final List<Object> 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));
}
}

View File

@ -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<String, String> first = new HashMap<>();
private static final Map<String, String> second = new HashMap<>();
private static Map<String, String> 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));
}
}

View File

@ -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<Object> first = new HashSet<Object>(Arrays.asList(new Object[] { "One", "Two", "Three" }));
private static final Set<Object> second = new HashSet<Object>(Arrays.asList(new Object[] { "Four", "Five", "Six" }));
private static final Set<Object> expected = new HashSet<Object>(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));
}
}

View File

@ -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<Integer> BASE_INTEGER_COLLECTION = Arrays.asList(9, 14, 2, 7, 1, 5, 8);
private static final Collection<Integer> EXPECTED_EVEN_FILTERED_COLLECTION = Arrays.asList(14, 2, 8);
@Test
public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() {
final Collection<String> baseStrings = Arrays.asList("java", "baeldung", "type", "example", "other");
Collection<String> filtered = StreamsCollectionFilter.filterCollectionHelperMethod(baseStrings, item -> item.length() == 4);
assertThat(filtered).containsExactlyInAnyOrder("java", "type");
}
@Test
public void givenAnIntegerCollection_whenFilteringEvenValues_thenObtainTheFilteredCollectionForAllCases() {
Collection<Integer> filteredWithStreams1 = StreamsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
Collection<Integer> filteredWithCollectionUtils = CollectionUtilsCollectionFilter.findEvenNumbers(new ArrayList<>(BASE_INTEGER_COLLECTION));
Collection<Integer> filteredWithEclipseCollections = EclipseCollectionsCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
Collection<Integer> filteredWithEclipseCollectionsUsingIterate = EclipseCollectionsCollectionFilter.findEvenNumbersUsingIterate(BASE_INTEGER_COLLECTION);
Collection<Integer> filteredWithGuava = GuavaCollectionFilter.findEvenNumbers(BASE_INTEGER_COLLECTION);
assertThat(filteredWithStreams1).hasSameElementsAs(filteredWithCollectionUtils)
.hasSameElementsAs(filteredWithEclipseCollections)
.hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate)
.hasSameElementsAs(filteredWithEclipseCollectionsUsingIterate)
.hasSameElementsAs(filteredWithGuava)
.hasSameElementsAs(EXPECTED_EVEN_FILTERED_COLLECTION);
}
}

View File

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

View File

@ -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<String> sauces = new ArrayList<>();
private ArrayList<String> cheeses = new ArrayList<>();
private ArrayList<String> vegetables = new ArrayList<>();
private ArrayList<ArrayList<String>> 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<ArrayList<String>> 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<ArrayList<String>> 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));
}
}

View File

@ -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<String> collection1 = Arrays.asList("Dog", "Cat");
Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");
Collection<String> 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<String> collection1 = Arrays.asList("Dog", "Cat");
Collection<String> collection2 = Arrays.asList("Bird", "Cow", "Moose");
Collection<String> 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<String> 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<Integer, String> 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<List<String>> 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<String> 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<String> animals = Arrays.asList("Dog", "Cat", "Cow", "Bird", "Moose", "Pig");
Collection<String> result1 = new ArrayList<>();
Collection<String> 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<Integer, List<String>> 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<String> 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<Integer, String> 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<String> result = Arrays.stream(animals.split("[,|.]")).map(String::trim).filter(next -> !next.isEmpty()).collect(Collectors.toList());
assertTrue(result.equals(Arrays.asList("Dog", "Cat", "Bird", "Cow")));
}
}

View File

@ -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<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Collection<String> collectionC = asList("W", "X");
Stream<String> combinedStream = Stream.concat(Stream.concat(collectionA.stream(), collectionB.stream()), collectionC.stream());
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
Assert.assertEquals(asList("S", "T", "U", "V", "W", "X"), collectionCombined);
}
@Test
public void givenUsingJava8_whenConcatenatingUsingflatMap_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Stream<String> combinedStream = Stream.of(collectionA, collectionB).flatMap(Collection::stream);
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
@Test
public void givenUsingGuava_whenConcatenatingUsingIterables_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = Iterables.unmodifiableIterable(Iterables.concat(collectionA, collectionB));
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
@Test
public void givenUsingJava7_whenConcatenatingUsingIterables_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = concat(collectionA, collectionB);
Collection<String> collectionCombined = makeListFromIterable(combinedIterables);
Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined);
}
public static <E> Iterable<E> concat(Iterable<? extends E> i1, Iterable<? extends E> i2) {
return new Iterable<E>() {
public Iterator<E> iterator() {
return new Iterator<E>() {
Iterator<? extends E> 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 <E> List<E> makeListFromIterable(Iterable<E> iter) {
List<E> list = new ArrayList<>();
for (E item : iter) {
list.add(item);
}
return list;
}
@Test
public void givenUsingApacheCommons_whenConcatenatingUsingUnion_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = CollectionUtils.union(collectionA, collectionB);
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
@Test
public void givenUsingApacheCommons_whenConcatenatingUsingChainedIterable_thenCorrect() {
Collection<String> collectionA = asList("S", "T");
Collection<String> collectionB = asList("U", "V");
Iterable<String> combinedIterables = IterableUtils.chainedIterable(collectionA, collectionB);
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
}
}

View File

@ -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<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@ -0,0 +1,38 @@
package com.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<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@ -0,0 +1,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<String> collection = null;
Stream<String> expResult = Stream.empty();
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
@Test
public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> expResult = Arrays.stream(new String[] { "a", "b", "c" });
Stream<String> result = instance.collectionAsStream(collection);
assertStreamEquals(expResult, result);
}
private static void assertStreamEquals(Stream<?> s1, Stream<?> s2) {
Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator();
while (iter1.hasNext() && iter2.hasNext())
assertEquals(iter1.next(), iter2.next());
assert !iter1.hasNext() && !iter2.hasNext();
}
}

View File

@ -0,0 +1,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<String> names;
Collection<String> expected;
Collection<String> 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<String> 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<String> filteredCollection = names
.stream()
.filter(e -> !e.startsWith("A"))
.collect(Collectors.toList());
assertThat(filteredCollection, is(expected));
}
@Test
public void givenCollectionOfNames_whenUsingStreamAndPartitioningByToFindNamesThatStartWithLetterA_shouldFind3MatchingAnd2NonMatching() {
Map<Boolean, List<String>> 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));
}
}

View File

@ -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<String> 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<Integer, String> 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<Map.Entry<Integer, String>> shuffledStudentEntries = new ArrayList<>(studentsById.entrySet());
Collections.shuffle(shuffledStudentEntries);
List<String> 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<String> students = new HashSet<>(Arrays.asList("Foo", "Bar", "Baz", "Qux"));
System.out.println("Set before shuffling:");
System.out.println(students);
List<String> studentList = new ArrayList<>(students);
Collections.shuffle(studentList);
System.out.println("Shuffled set elements:");
System.out.println(studentList);
}
@Test
public void whenShufflingWithSameRandomness_thenElementsAreShuffledDeterministically() {
List<String> students_1 = Arrays.asList("Foo", "Bar", "Baz", "Qux");
List<String> 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);
}
}

View File

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

View File

@ -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<Integer, String> 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<Employee> 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<Integer> 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<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
entries.sort(Comparator.comparing(Entry::getKey));
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
for (Map.Entry<Integer, String> 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<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
entries.sort(Comparator.comparing(Entry::getValue));
HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
for (Map.Entry<Integer, String> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
assertTrue(Arrays.equals(sortedMap.values()
.toArray(), sortedValues));
}
@Test
public void givenSet_whenUsingSort_thenSortedSet() {
HashSet<Integer> integersSet = new LinkedHashSet<>(Ints.asList(toSort));
HashSet<Integer> descSortedIntegersSet = new LinkedHashSet<>(Arrays.asList(255, 200, 123, 89, 88, 66, 7, 5, 1));
ArrayList<Integer> list = new ArrayList<>(integersSet);
list.sort(Comparator.reverseOrder());
integersSet = new LinkedHashSet<>(list);
assertTrue(Arrays.equals(integersSet.toArray(), descSortedIntegersSet.toArray()));
}
}