This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
## Guava Collections
This module contains articles about Google Guava collections
### Relevant Articles:
- [Guava Collections Cookbook](https://www.baeldung.com/guava-collections)
- [Guava Ordering Cookbook](https://www.baeldung.com/guava-order)
- [Guide to Guavas Ordering](https://www.baeldung.com/guava-ordering)
- [Hamcrest Collections Cookbook](https://www.baeldung.com/hamcrest-collections-arrays)
- [Partition a List in Java](https://www.baeldung.com/java-list-split)
- [Filtering and Transforming Collections in Guava](https://www.baeldung.com/guava-filter-and-transform-a-collection)
- [Guava Join and Split Collections](https://www.baeldung.com/guava-joiner-and-splitter-tutorial)
- [Guava Lists](https://www.baeldung.com/guava-lists)
- [Guide to Guava MinMaxPriorityQueue and EvictingQueue](https://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue)
- [Guide to Guava Table](https://www.baeldung.com/guava-table)
+63
View File
@@ -0,0 +1,63 @@
<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>guava-collections</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>guava-collections</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<!-- utils -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>${java-hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>guava-collections</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<!-- util -->
<commons-collections4.version>4.1</commons-collections4.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
</properties>
</project>
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,189 @@
package com.baeldung.guava.collections;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.junit.Test;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
@SuppressWarnings("unused")
public class GuavaCollectionsExamplesUnitTest {
// tests
@Test
public final void whenDowncastingGenerifiedCollectionToNewGenerifiedCollection_thenCastIsOK() {
final class CastFunction<F, T extends F> implements Function<F, T> {
@SuppressWarnings("unchecked")
@Override
public final T apply(final F from) {
return (T) from;
}
}
final List<Number> originalList = Lists.newArrayList();
final List<Integer> selectedProducts = Lists.transform(originalList, new CastFunction<Number, Integer>());
System.out.println(selectedProducts);
}
@SuppressWarnings({ "unchecked" })
@Test
public final void whenDowncastingGenerifiedCollectionToNewGenerifiedCollection_thenCastIsOK2() {
final List<Number> originalList = Lists.newArrayList();
final List<Integer> selectedProducts = (List<Integer>) (List<? extends Number>) originalList;
System.out.println(selectedProducts);
}
@Test
public final void whenAddingAnIterableToACollection_thenAddedOK() {
final Iterable<String> iter = Lists.newArrayList();
final Collection<String> collector = Lists.newArrayList();
Iterables.addAll(collector, iter);
}
//
@Test
public final void whenCheckingIfCollectionContainsElementsByCustomMatch1_thenContains() {
final Iterable<String> theCollection = Lists.newArrayList("a", "bc", "def");
final boolean contains = Iterables.any(theCollection, new Predicate<String>() {
@Override
public final boolean apply(final String input) {
return input.length() == 1;
}
});
assertTrue(contains);
}
@Test
public final void whenCheckingIfCollectionContainsElementsByCustomMatch2_thenContains() {
final Set<String> theCollection = Sets.newHashSet("a", "bc", "def");
final boolean contains = !Sets.filter(theCollection, new Predicate<String>() {
@Override
public final boolean apply(final String input) {
return input.length() == 1;
}
}).isEmpty();
assertTrue(contains);
}
@Test
public final void whenCheckingIfCollectionContainsElementsByCustomMatch3_thenContains() {
final Iterable<String> theCollection = Sets.newHashSet("a", "bc", "def");
final boolean contains = Iterables.find(theCollection, new Predicate<String>() {
@Override
public final boolean apply(final String input) {
return input.length() == 1;
}
}) != null;
assertTrue(contains);
}
//
@Test(expected = NoSuchElementException.class)
public final void givenNoSearchResult_whenFindingElementInIterable_thenException() {
final Iterable<String> theCollection = Sets.newHashSet("abcd", "efgh", "ijkl");
final String found = Iterables.find(theCollection, new Predicate<String>() {
@Override
public final boolean apply(final String input) {
return input.length() == 1;
}
});
assertNull(found);
}
@Test
public final void givenNoSearchResult_whenFindingElementInIterableWithSpecifiedReturn_thenNoException() {
final Iterable<String> theCollection = Sets.newHashSet("abcd", "efgh", "ijkl");
final Predicate<String> inputOfLengthOne = new Predicate<String>() {
@Override
public final boolean apply(final String input) {
return input.length() == 1;
}
};
final String found = Iterables.find(theCollection, inputOfLengthOne, null);
assertNull(found);
}
// purge of nulls
@Test
public final void givenListContainsNulls_whenPurgedOfNulls_thenNoLongerContainsNulls() {
final List<String> values = Lists.newArrayList("a", null, "b", "c");
final Iterable<String> withoutNulls = Iterables.filter(values, Predicates.notNull());
System.out.println(withoutNulls);
}
// immutable collections
@Test
public final void whenCreatingImuutableCollections_thenNoExceptions() {
final ImmutableList<String> immutableList = ImmutableList.of("a", "b", "c");
final ImmutableSet<String> immutableSet = ImmutableSet.of("a", "b", "c");
final ImmutableMap<String, String> imuttableMap = ImmutableMap.of("k1", "v1", "k2", "v2", "k3", "v3");
}
@Test
public final void whenTransformingCollectionsToImmutable_thenNoExceptions() {
final List<String> muttableList = Lists.newArrayList();
final ImmutableList<String> immutableList = ImmutableList.copyOf(muttableList);
final Set<String> muttableSet = Sets.newHashSet();
final ImmutableSet<String> immutableSet = ImmutableSet.copyOf(muttableSet);
final Map<String, String> muttableMap = Maps.newHashMap();
final ImmutableMap<String, String> imuttableMap = ImmutableMap.copyOf(muttableMap);
}
@Test
public final void whenTransformingCollectionsToImmutableViaBuilders_thenNoExceptions() {
final List<String> muttableList = Lists.newArrayList();
final ImmutableList<String> immutableList = ImmutableList.<String> builder().addAll(muttableList).build();
final Set<String> muttableSet = Sets.newHashSet();
final ImmutableSet<String> immutableSet = ImmutableSet.<String> builder().addAll(muttableSet).build();
final Map<String, String> muttableMap = Maps.newHashMap();
final ImmutableMap<String, String> imuttableMap = ImmutableMap.<String, String> builder().putAll(muttableMap).build();
}
// unmodifiable
@Test(expected = UnsupportedOperationException.class)
public final void givenUnmodifiableViewOverIterable_whenTryingToRemove_thenNotAllowed() {
final List<Integer> numbers = Lists.newArrayList(1, 2, 3);
final Iterable<Integer> unmodifiableIterable = Iterables.unmodifiableIterable(numbers);
final Iterator<Integer> iterator = unmodifiableIterable.iterator();
if (iterator.hasNext()) {
iterator.remove();
}
}
}
@@ -0,0 +1,206 @@
package com.baeldung.guava.filtertransform;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
public class GuavaFilterTransformCollectionsUnitTest {
@Test
public void whenFilterWithIterables_thenFiltered() {
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Iterable<String> result = Iterables.filter(names, Predicates.containsPattern("a"));
assertThat(result, containsInAnyOrder("Jane", "Adam"));
}
@Test
public void whenFilterWithCollections2_thenFiltered() {
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<String> result = Collections2.filter(names, Predicates.containsPattern("a"));
assertEquals(2, result.size());
assertThat(result, containsInAnyOrder("Jane", "Adam"));
result.add("anna");
assertEquals(5, names.size());
}
@Test(expected = IllegalArgumentException.class)
public void givenFilteredCollection_whenAddingInvalidElement_thenException() {
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<String> result = Collections2.filter(names, Predicates.containsPattern("a"));
result.add("elvis");
}
//
@Test
public void whenFilterCollectionWithCustomPredicate_thenFiltered() {
final Predicate<String> predicate = new Predicate<String>() {
@Override
public final boolean apply(final String input) {
return input.startsWith("A") || input.startsWith("J");
}
};
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<String> result = Collections2.filter(names, predicate);
assertEquals(3, result.size());
assertThat(result, containsInAnyOrder("John", "Jane", "Adam"));
}
//
@Test
public void whenRemoveNullFromCollection_thenRemoved() {
final List<String> names = Lists.newArrayList("John", null, "Jane", null, "Adam", "Tom");
final Collection<String> result = Collections2.filter(names, Predicates.notNull());
assertEquals(4, result.size());
assertThat(result, containsInAnyOrder("John", "Jane", "Adam", "Tom"));
}
//
@Test
public void whenCheckingIfAllElementsMatchACondition_thenCorrect() {
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
boolean result = Iterables.all(names, Predicates.containsPattern("n|m"));
assertTrue(result);
result = Iterables.all(names, Predicates.containsPattern("a"));
assertFalse(result);
}
//
@Test
public void whenTransformingWithIterables_thenTransformed() {
final Function<String, Integer> function = new Function<String, Integer>() {
@Override
public final Integer apply(final String input) {
return input.length();
}
};
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Iterable<Integer> result = Iterables.transform(names, function);
assertThat(result, contains(4, 4, 4, 3));
}
//
@Test
public void whenTransformWithCollections2_thenTransformed() {
final Function<String, Integer> function = new Function<String, Integer>() {
@Override
public final Integer apply(final String input) {
return input.length();
}
};
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<Integer> result = Collections2.transform(names, function);
assertEquals(4, result.size());
assertThat(result, contains(4, 4, 4, 3));
result.remove(3);
assertEquals(3, names.size());
}
//
@Test
public void whenCreatingAFunctionFromAPredicate_thenCorrect() {
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<Boolean> result = Collections2.transform(names, Functions.forPredicate(Predicates.containsPattern("m")));
assertEquals(4, result.size());
assertThat(result, contains(false, false, true, true));
}
//
@Test
public void whenTransformingUsingComposedFunction_thenTransformed() {
final Function<String, Integer> f1 = new Function<String, Integer>() {
@Override
public final Integer apply(final String input) {
return input.length();
}
};
final Function<Integer, Boolean> f2 = new Function<Integer, Boolean>() {
@Override
public final Boolean apply(final Integer input) {
return input % 2 == 0;
}
};
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<Boolean> result = Collections2.transform(names, Functions.compose(f2, f1));
assertEquals(4, result.size());
assertThat(result, contains(true, true, true, false));
}
//
@Test
public void whenFilteringAndTransformingCollection_thenCorrect() {
final Predicate<String> predicate = new Predicate<String>() {
@Override
public final boolean apply(final String input) {
return input.startsWith("A") || input.startsWith("T");
}
};
final Function<String, Integer> func = new Function<String, Integer>() {
@Override
public final Integer apply(final String input) {
return input.length();
}
};
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<Integer> result = FluentIterable.from(names).filter(predicate).transform(func).toList();
assertEquals(2, result.size());
assertThat(result, containsInAnyOrder(4, 3));
}
//
@Test
public void whenFilterUsingMultiplePredicates_thenFiltered() {
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<String> result = Collections2.filter(names, Predicates.or(Predicates.containsPattern("J"), Predicates.not(Predicates.containsPattern("a"))));
assertEquals(3, result.size());
assertThat(result, containsInAnyOrder("John", "Jane", "Tom"));
}
}
@@ -0,0 +1,214 @@
package com.baeldung.guava.joinsplit;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.*;
import com.google.common.collect.*;
import org.junit.Test;
import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
public class GuavaStringUnitTest {
@Test
public void whenConvertListToString_thenConverted() {
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final String result = Joiner.on(",").join(names);
assertEquals(result, "John,Jane,Adam,Tom");
}
@Test
public void whenConvertListToStringAndSkipNull_thenConverted() {
final List<String> names = Lists.newArrayList("John", null, "Jane", "Adam", "Tom");
final String result = Joiner.on(",").skipNulls().join(names);
assertEquals(result, "John,Jane,Adam,Tom");
}
@Test
public void whenConvertMapToString_thenConverted() {
final Map<String, Integer> salary = Maps.newHashMap();
salary.put("John", 1000);
salary.put("Jane", 1500);
final String result = Joiner.on(" , ").withKeyValueSeparator(" = ").join(salary);
assertThat(result, containsString("John = 1000"));
assertThat(result, containsString("Jane = 1500"));
}
@Test
public void whenJoinNestedCollections_thenJoined() {
final List<ArrayList<String>> nested = Lists.newArrayList(Lists.newArrayList("apple", "banana", "orange"), Lists.newArrayList("cat", "dog", "bird"), Lists.newArrayList("John", "Jane", "Adam"));
final String result = Joiner.on(";").join(Iterables.transform(nested, new Function<List<String>, String>() {
@Override
public final String apply(final List<String> input) {
return Joiner.on("-").join(input);
}
}));
assertThat(result, containsString("apple-banana-orange"));
assertThat(result, containsString("cat-dog-bird"));
assertThat(result, containsString("John-Jane-Adam"));
}
@Test
public void whenUseForNull_thenUsed() {
final List<String> names = Lists.newArrayList("John", null, "Jane", "Adam", "Tom");
final String result = Joiner.on(",").useForNull("nameless").join(names);
assertEquals(result, "John,nameless,Jane,Adam,Tom");
}
@Test
public void whenCreateListFromString_thenCreated() {
final String input = "apple - banana - orange";
final List<String> result = Splitter.on("-").trimResults().splitToList(input);
assertThat(result, contains("apple", "banana", "orange"));
}
@Test
public void whenCreateMapFromString_thenCreated() {
final String input = "John=first,Adam=second";
final Map<String, String> result = Splitter.on(",").withKeyValueSeparator("=").split(input);
assertEquals("first", result.get("John"));
assertEquals("second", result.get("Adam"));
}
@Test
public void whenSplitStringOnMultipleSeparator_thenSplit() {
final String input = "apple.banana,,orange,,.";
final List<String> result = Splitter.onPattern("[.,]").omitEmptyStrings().splitToList(input);
assertThat(result, contains("apple", "banana", "orange"));
}
@Test
public void whenSplitStringOnSpecificLength_thenSplit() {
final String input = "Hello world";
final List<String> result = Splitter.fixedLength(3).splitToList(input);
assertThat(result, contains("Hel", "lo ", "wor", "ld"));
}
@Test
public void whenLimitSplitting_thenLimited() {
final String input = "a,b,c,d,e";
final List<String> result = Splitter.on(",").limit(4).splitToList(input);
assertEquals(4, result.size());
assertThat(result, contains("a", "b", "c", "d,e"));
}
@Test
public void whenRemoveSpecialCharacters_thenRemoved() {
final String input = "H*el.lo,}12";
final CharMatcher matcher = CharMatcher.JAVA_LETTER_OR_DIGIT;
final String result = matcher.retainFrom(input);
assertEquals("Hello12", result);
}
@Test
public void whenRemoveNonASCIIChars_thenRemoved() {
final String input = "あhello₤";
String result = CharMatcher.ASCII.retainFrom(input);
assertEquals("hello", result);
result = CharMatcher.inRange('0', 'z').retainFrom(input);
assertEquals("hello", result);
}
@Test
public void whenValidateString_thenValid() {
final String input = "hello";
boolean result = CharMatcher.JAVA_LOWER_CASE.matchesAllOf(input);
assertTrue(result);
result = CharMatcher.is('e').matchesAnyOf(input);
assertTrue(result);
result = CharMatcher.JAVA_DIGIT.matchesNoneOf(input);
assertTrue(result);
}
@Test
public void whenTrimString_thenTrimmed() {
final String input = "---hello,,,";
String result = CharMatcher.is('-').trimLeadingFrom(input);
assertEquals("hello,,,", result);
result = CharMatcher.is(',').trimTrailingFrom(input);
assertEquals("---hello", result);
result = CharMatcher.anyOf("-,").trimFrom(input);
assertEquals("hello", result);
}
@Test
public void whenCollapseFromString_thenCollapsed() {
final String input = " hel lo ";
String result = CharMatcher.is(' ').collapseFrom(input, '-');
assertEquals("-hel-lo-", result);
result = CharMatcher.is(' ').trimAndCollapseFrom(input, '-');
assertEquals("hel-lo", result);
}
@Test
public void whenReplaceFromString_thenReplaced() {
final String input = "apple-banana.";
String result = CharMatcher.anyOf("-.").replaceFrom(input, '!');
assertEquals("apple!banana!", result);
result = CharMatcher.is('-').replaceFrom(input, " and ");
assertEquals("apple and banana.", result);
}
@Test
public void whenCountCharInString_thenCorrect() {
final String input = "a, c, z, 1, 2";
int result = CharMatcher.is(',').countIn(input);
assertEquals(4, result);
result = CharMatcher.inRange('a', 'h').countIn(input);
assertEquals(2, result);
}
@Test
public void whenRemoveCharsNotInCharset_thenRemoved() {
final Charset charset = Charset.forName("cp437");
final CharsetEncoder encoder = charset.newEncoder();
final Predicate<Character> inRange = new Predicate<Character>() {
@Override
public boolean apply(final Character c) {
return encoder.canEncode(c);
}
};
final String result = CharMatcher.forPredicate(inRange).retainFrom("helloは");
assertEquals("hello", result);
}
}
@@ -0,0 +1,82 @@
package com.baeldung.guava.lists;
import com.google.common.base.Predicates;
import com.google.common.collect.*;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.contains;
public class GuavaListsUnitTest {
@Test
public void whenCreateList_thenCreated() {
final List<String> names = Lists.newArrayList("John", "Adam", "Jane");
names.add("Tom");
assertEquals(4, names.size());
names.remove("Adam");
assertThat(names, contains("John", "Jane", "Tom"));
}
@Test
public void whenReverseList_thenReversed() {
final List<String> names = Lists.newArrayList("John", "Adam", "Jane");
final List<String> reversed = Lists.reverse(names);
assertThat(reversed, contains("Jane", "Adam", "John"));
}
@Test
public void whenCreateCharacterListFromString_thenCreated() {
final List<Character> chars = Lists.charactersOf("John");
assertEquals(4, chars.size());
assertThat(chars, contains('J', 'o', 'h', 'n'));
}
@Test
public void whenPartitionList_thenPartitioned() {
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom", "Viki", "Tyler");
final List<List<String>> result = Lists.partition(names, 2);
assertEquals(3, result.size());
assertThat(result.get(0), contains("John", "Jane"));
assertThat(result.get(1), contains("Adam", "Tom"));
assertThat(result.get(2), contains("Viki", "Tyler"));
}
@Test
public void whenRemoveDuplicatesFromList_thenRemoved() {
final List<Character> chars = Lists.newArrayList('h', 'e', 'l', 'l', 'o');
assertEquals(5, chars.size());
final List<Character> result = ImmutableSet.copyOf(chars).asList();
assertThat(result, contains('h', 'e', 'l', 'o'));
}
@Test
public void whenRemoveNullFromList_thenRemoved() {
final List<String> names = Lists.newArrayList("John", null, "Adam", null, "Jane");
Iterables.removeIf(names, Predicates.isNull());
assertEquals(3, names.size());
assertThat(names, contains("John", "Adam", "Jane"));
}
@Test
public void whenCreateImmutableList_thenCreated() {
final List<String> names = Lists.newArrayList("John", "Adam", "Jane");
names.add("Tom");
assertEquals(4, names.size());
final ImmutableList<String> immutable = ImmutableList.copyOf(names);
assertThat(immutable, contains("John", "Adam", "Jane", "Tom"));
}
}
@@ -0,0 +1,179 @@
package com.baeldung.guava.ordering;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Ints;
public class GuavaOrderingExamplesUnitTest {
private final class OrderingByLenght extends Ordering<String> {
@Override
public final int compare(final String s1, final String s2) {
return Ints.compare(s1.length(), s2.length());
}
}
// tests
// dealing with null
@Test
public final void givenCollectionWithNulls_whenSortingWithNullsLast_thenNullsAreLast() {
final List<Integer> toSort = Arrays.asList(3, 5, 4, null, 1, 2);
Collections.sort(toSort, Ordering.natural().nullsLast());
assertThat(toSort.get(toSort.size() - 1), nullValue());
}
@Test
public final void givenCollectionWithNulls_whenSortingWithNullsFirst_thenNullsAreFirst() {
final List<Integer> toSort = Arrays.asList(3, 5, 4, null, 1, 2);
Collections.sort(toSort, Ordering.natural().nullsFirst());
assertThat(toSort.get(0), nullValue());
}
@Test
public final void whenCollectionIsSortedNullsLastReversed_thenNullAreFirst() {
final List<Integer> toSort = Arrays.asList(3, 5, 4, null, 1, 2);
Collections.sort(toSort, Ordering.natural().nullsLast().reverse());
assertThat(toSort.get(0), nullValue());
}
// natural ordering
@Test
public final void whenSortingWithNaturalOrdering_thenCorectlySorted() {
final List<Integer> toSort = Arrays.asList(3, 5, 4, 1, 2);
Collections.sort(toSort, Ordering.natural());
assertTrue(Ordering.natural().isOrdered(toSort));
}
// checking string ordering
@Test
public final void givenCollectionContainsDuplicates_whenCheckingStringOrdering_thenNo() {
final List<Integer> toSort = Arrays.asList(3, 5, 4, 2, 1, 2);
Collections.sort(toSort, Ordering.natural());
assertFalse(Ordering.natural().isStrictlyOrdered(toSort));
}
// custom - by length
@Test
public final void givenCollectionIsSorted_whenUsingOrderingApiToCheckOrder_thenCheckCanBePerformed() {
final List<String> toSort = Arrays.asList("zz", "aa", "b", "ccc");
final Ordering<String> byLength = new OrderingByLenght();
Collections.sort(toSort, byLength);
final Ordering<String> expectedOrder = Ordering.explicit(Lists.newArrayList("b", "zz", "aa", "ccc"));
assertTrue(expectedOrder.isOrdered(toSort));
}
@Test
public final void whenSortingCollectionsOfStringsByLenght_thenCorrectlySorted() {
final List<String> toSort = Arrays.asList("zz", "aa", "b", "ccc");
final Ordering<String> byLength = new OrderingByLenght();
Collections.sort(toSort, byLength);
final Ordering<String> expectedOrder = Ordering.explicit(Lists.newArrayList("b", "zz", "aa", "ccc"));
assertTrue(expectedOrder.isOrdered(toSort));
}
@Test
public final void whenSortingCollectionsOfStringsByLenghtWithSecondaryNaturalOrdering_thenCorrectlySorted() {
final List<String> toSort = Arrays.asList("zz", "aa", "b", "ccc");
final Ordering<String> byLength = new OrderingByLenght();
Collections.sort(toSort, byLength.compound(Ordering.natural()));
final Ordering<String> expectedOrder = Ordering.explicit(Lists.newArrayList("b", "aa", "zz", "ccc"));
assertTrue(expectedOrder.isOrdered(toSort));
}
@Test
public final void whenSortingCollectionsWithComplexOrderingExample_thenCorrectlySorted() {
final List<String> toSort = Arrays.asList("zz", "aa", null, "b", "ccc");
Collections.sort(toSort, new OrderingByLenght().reverse().compound(Ordering.natural()).nullsLast());
System.out.println(toSort);
}
// sorted copy
@Test
public final void givenUnorderdList_whenRetrievingSortedCopy_thenSorted() {
final List<String> toSort = Arrays.asList("aa", "b", "ccc");
final List<String> sortedCopy = new OrderingByLenght().sortedCopy(toSort);
final Ordering<String> expectedOrder = Ordering.explicit(Lists.newArrayList("b", "aa", "ccc"));
assertFalse(expectedOrder.isOrdered(toSort));
assertTrue(expectedOrder.isOrdered(sortedCopy));
}
// to string
@Test
public final void givenUnorderdList_whenUsingToStringForSortingObjects_thenSortedWithToString() {
final List<Integer> toSort = Arrays.asList(1, 2, 11);
Collections.sort(toSort, Ordering.usingToString());
final Ordering<Integer> expectedOrder = Ordering.explicit(Lists.newArrayList(1, 11, 2));
assertTrue(expectedOrder.isOrdered(toSort));
}
// binary search
@Test
public final void whenPerformingBinarySearch_thenFound() {
final List<Integer> toSort = Arrays.asList(1, 2, 11);
Collections.sort(toSort, Ordering.usingToString());
final int found = Ordering.usingToString().binarySearch(toSort, 2);
System.out.println(found);
}
// min/max without actually sorting
@Test
public final void whenFindingTheMinimalElementWithoutSorting_thenFound() {
final List<Integer> toSort = Arrays.asList(2, 1, 11, 100, 8, 14);
final int found = Ordering.natural().min(toSort);
assertThat(found, equalTo(1));
}
@Test
public final void whenFindingTheFirstFewElements_thenCorrect() {
final List<Integer> toSort = Arrays.asList(2, 1, 11, 100, 8, 14);
final List<Integer> leastOf = Ordering.natural().leastOf(toSort, 3);
final List<Integer> expected = Lists.newArrayList(1, 2, 8);
assertThat(expected, equalTo(leastOf));
}
// order the results of a Function
@Test
public final void givenListOfNumbers_whenRunningAToStringFunctionThenSorting_thenCorrect() {
final List<Integer> toSort = Arrays.asList(2, 1, 11, 100, 8, 14);
final Ordering<Object> ordering = Ordering.natural().onResultOf(Functions.toStringFunction());
final List<Integer> sortedCopy = ordering.sortedCopy(toSort);
final List<Integer> expected = Lists.newArrayList(1, 100, 11, 14, 2, 8);
assertThat(expected, equalTo(sortedCopy));
}
}
@@ -0,0 +1,91 @@
package com.baeldung.guava.ordering;
import com.google.common.base.Function;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Ints;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class GuavaOrderingUnitTest {
@Test
public void givenListOfIntegers_whenCreateNaturalOrderOrdering_shouldSortProperly() {
//given
List<Integer> integers = Arrays.asList(3, 2, 1);
//when
integers.sort(Ordering.natural());
//then
assertEquals(Arrays.asList(1, 2, 3), integers);
}
@Test
public void givenListOfPersonObject_whenSortedUsingCustomOrdering_shouldSortProperly() {
//given
List<Person> persons = Arrays.asList(new Person("Michael", 10), new Person("Alice", 3));
Ordering<Person> orderingByAge = new Ordering<Person>() {
@Override
public int compare(Person p1, Person p2) {
return Ints.compare(p1.age, p2.age);
}
};
//when
persons.sort(orderingByAge);
//then
assertEquals(Arrays.asList(new Person("Alice", 3), new Person("Michael", 10)), persons);
}
@Test
public void givenListOfPersonObject_whenSortedUsingChainedOrdering_shouldSortPropely() {
//given
List<Person> persons = Arrays.asList(new Person("Michael", 10), new Person("Alice", 3), new Person("Thomas", null));
Ordering<Person> ordering = Ordering.natural().nullsFirst().onResultOf(new Function<Person, Comparable>() {
@Override
public Comparable apply(Person person) {
return person.age;
}
});
//when
persons.sort(ordering);
//then
assertEquals(Arrays.asList(new Person("Thomas", null), new Person("Alice", 3), new Person("Michael", 10)), persons);
}
class Person {
private final String name;
private final Integer age;
private Person(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (name != null ? !name.equals(person.name) : person.name != null) return false;
return age != null ? age.equals(person.age) : person.age == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (age != null ? age.hashCode() : 0);
return result;
}
}
}
@@ -0,0 +1,43 @@
package com.baeldung.guava.partition;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.apache.commons.collections4.ListUtils;
import org.junit.Test;
import com.google.common.collect.Lists;
public class CollectionApachePartitionUnitTest {
// tests - apache common collections
@Test
public final void givenList_whenParitioningIntoNSublists_thenCorrect() {
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
final List<List<Integer>> subSets = ListUtils.partition(intList, 3);
// When
final List<Integer> lastPartition = subSets.get(2);
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
assertThat(subSets.size(), equalTo(3));
assertThat(lastPartition, equalTo(expectedLastPartition));
}
@Test
public final void givenListPartitioned_whenOriginalListIsModified_thenPartitionsChange() {
// Given
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
final List<List<Integer>> subSets = ListUtils.partition(intList, 3);
// When
intList.add(9);
final List<Integer> lastPartition = subSets.get(2);
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8, 9);
assertThat(lastPartition, equalTo(expectedLastPartition));
}
}
@@ -0,0 +1,56 @@
package com.baeldung.guava.partition;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
public class CollectionGuavaPartitionUnitTest {
// tests - guava
@Test
public final void givenList_whenParitioningIntoNSublists_thenCorrect() {
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
final List<List<Integer>> subSets = Lists.partition(intList, 3);
// When
final List<Integer> lastPartition = subSets.get(2);
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
assertThat(subSets.size(), equalTo(3));
assertThat(lastPartition, equalTo(expectedLastPartition));
}
@Test
public final void givenListPartitioned_whenOriginalListIsModified_thenPartitionsChangeAsWell() {
// Given
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
final List<List<Integer>> subSets = Lists.partition(intList, 3);
// When
intList.add(9);
final List<Integer> lastPartition = subSets.get(2);
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8, 9);
assertThat(lastPartition, equalTo(expectedLastPartition));
}
@Test
public final void givenCollection_whenParitioningIntoNSublists_thenCorrect() {
final Collection<Integer> intCollection = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
final Iterable<List<Integer>> subSets = Iterables.partition(intCollection, 3);
// When
final List<Integer> firstPartition = subSets.iterator().next();
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(1, 2, 3);
assertThat(firstPartition, equalTo(expectedLastPartition));
}
}
@@ -0,0 +1,70 @@
package com.baeldung.guava.partition;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Test;
import com.google.common.collect.Lists;
public class CollectionJavaPartitionUnitTest {
// java8 groupBy
@Test
public final void givenList_whenParitioningIntoNSublistsUsingGroupingBy_thenCorrect() {
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
final Map<Integer, List<Integer>> groups = intList.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3));
final List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
// When
final List<Integer> lastPartition = subSets.get(2);
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
assertThat(subSets.size(), equalTo(3));
assertThat(lastPartition, equalTo(expectedLastPartition));
// intList.add(9);
// System.out.println(groups.values());
}
// java8 partitionBy
@Test
public final void givenList_whenParitioningIntoSublistsUsingPartitionBy_thenCorrect() {
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
final Map<Boolean, List<Integer>> groups = intList.stream().collect(Collectors.partitioningBy(s -> s > 6));
final List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
// When
final List<Integer> lastPartition = subSets.get(1);
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
assertThat(subSets.size(), equalTo(2));
assertThat(lastPartition, equalTo(expectedLastPartition));
// intList.add(9);
// System.out.println(groups.values());
}
// java8 split by separator
@Test
public final void givenList_whenSplittingBySeparator_thenCorrect() {
final List<Integer> intList = Lists.newArrayList(1, 2, 3, 0, 4, 5, 6, 0, 7, 8);
final int[] indexes = Stream.of(IntStream.of(-1), IntStream.range(0, intList.size()).filter(i -> intList.get(i) == 0), IntStream.of(intList.size())).flatMapToInt(s -> s).toArray();
final List<List<Integer>> subSets = IntStream.range(0, indexes.length - 1).mapToObj(i -> intList.subList(indexes[i] + 1, indexes[i + 1])).collect(Collectors.toList());
// When
final List<Integer> lastPartition = subSets.get(2);
final List<Integer> expectedLastPartition = Lists.<Integer> newArrayList(7, 8);
assertThat(subSets.size(), equalTo(3));
assertThat(lastPartition, equalTo(expectedLastPartition));
}
}
@@ -0,0 +1,31 @@
package com.baeldung.guava.queues;
import com.google.common.collect.EvictingQueue;
import org.junit.Test;
import java.util.Queue;
import java.util.stream.IntStream;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class EvictingQueueUnitTest {
@Test
public void givenEvictingQueue_whenAddElementToFull_thenShouldEvictOldestItem() {
//given
Queue<Integer> evictingQueue = EvictingQueue.create(10);
//when
IntStream.range(0, 10).forEach(evictingQueue::add);
//then
assertThat(evictingQueue).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
//and
evictingQueue.add(100);
//then
assertThat(evictingQueue).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 100);
}
}
@@ -0,0 +1,66 @@
package com.baeldung.guava.queues;
import com.google.common.collect.MinMaxPriorityQueue;
import org.junit.Test;
import java.util.Comparator;
import java.util.stream.IntStream;
import static org.assertj.core.api.Assertions.assertThat;
public class MinMaxPriorityQueueUnitTest {
@Test
public void givenMinMaxPriorityQueue_whenAddElementToFull_thenShouldEvictGreatestItem() {
//given
MinMaxPriorityQueue<CustomClass> queue = MinMaxPriorityQueue
.orderedBy(Comparator.comparing(CustomClass::getValue))
.maximumSize(10)
.create();
//when
IntStream
.iterate(10, i -> i - 1)
.limit(10)
.forEach(i -> queue.add(new CustomClass(i)));
//then
assertThat(queue.peekFirst().getValue()).isEqualTo(1);
assertThat(queue.peekLast().getValue()).isEqualTo(10);
//and
queue.add(new CustomClass(-1));
//then
assertThat(queue.peekFirst().getValue()).isEqualTo(-1);
assertThat(queue.peekLast().getValue()).isEqualTo(9);
//and
queue.add(new CustomClass(100));
assertThat(queue.peekFirst().getValue()).isEqualTo(-1);
assertThat(queue.peekLast().getValue()).isEqualTo(9);
}
class CustomClass {
private final Integer value;
CustomClass(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
@Override
public String toString() {
return "CustomClass{" +
"value=" + value +
'}';
}
}
}
@@ -0,0 +1,178 @@
package com.baeldung.guava.table;
import static org.assertj.core.api.Assertions.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import com.google.common.collect.ArrayTable;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Lists;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
public class GuavaTableUnitTest {
@Test
public void givenTable_whenGet_returnsSuccessfully() {
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
universityCourseSeatTable.put("Mumbai", "IT", 60);
universityCourseSeatTable.put("Harvard", "Electrical", 60);
universityCourseSeatTable.put("Harvard", "IT", 120);
final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
final Integer seatCountForNoEntry = universityCourseSeatTable.get("Oxford", "IT");
assertThat(seatCount).isEqualTo(60);
assertThat(seatCountForNoEntry).isEqualTo(null);
}
@Test
public void givenTable_whenContains_returnsSuccessfully() {
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
universityCourseSeatTable.put("Mumbai", "IT", 60);
universityCourseSeatTable.put("Harvard", "Electrical", 60);
universityCourseSeatTable.put("Harvard", "IT", 120);
final boolean entryIsPresent = universityCourseSeatTable.contains("Mumbai", "IT");
final boolean entryIsAbsent = universityCourseSeatTable.contains("Oxford", "IT");
final boolean courseIsPresent = universityCourseSeatTable.containsColumn("IT");
final boolean universityIsPresent = universityCourseSeatTable.containsRow("Mumbai");
final boolean seatCountIsPresent = universityCourseSeatTable.containsValue(60);
assertThat(entryIsPresent).isEqualTo(true);
assertThat(entryIsAbsent).isEqualTo(false);
assertThat(courseIsPresent).isEqualTo(true);
assertThat(universityIsPresent).isEqualTo(true);
assertThat(seatCountIsPresent).isEqualTo(true);
}
@Test
public void givenTable_whenRemove_returnsSuccessfully() {
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
universityCourseSeatTable.put("Mumbai", "IT", 60);
final int seatCount = universityCourseSeatTable.remove("Mumbai", "IT");
assertThat(seatCount).isEqualTo(60);
assertThat(universityCourseSeatTable.remove("Mumbai", "IT")).isEqualTo(null);
}
@Test
public void givenTable_whenColumn_returnsSuccessfully() {
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
universityCourseSeatTable.put("Mumbai", "IT", 60);
universityCourseSeatTable.put("Harvard", "Electrical", 60);
universityCourseSeatTable.put("Harvard", "IT", 120);
final Map<String, Integer> universitySeatMap = universityCourseSeatTable.column("IT");
assertThat(universitySeatMap).hasSize(2);
assertThat(universitySeatMap.get("Mumbai")).isEqualTo(60);
assertThat(universitySeatMap.get("Harvard")).isEqualTo(120);
}
@Test
public void givenTable_whenColumnMap_returnsSuccessfully() {
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
universityCourseSeatTable.put("Mumbai", "IT", 60);
universityCourseSeatTable.put("Harvard", "Electrical", 60);
universityCourseSeatTable.put("Harvard", "IT", 120);
final Map<String, Map<String, Integer>> courseKeyUniversitySeatMap = universityCourseSeatTable.columnMap();
assertThat(courseKeyUniversitySeatMap).hasSize(3);
assertThat(courseKeyUniversitySeatMap.get("IT")).hasSize(2);
assertThat(courseKeyUniversitySeatMap.get("Electrical")).hasSize(1);
assertThat(courseKeyUniversitySeatMap.get("Chemical")).hasSize(1);
}
@Test
public void givenTable_whenRow_returnsSuccessfully() {
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
universityCourseSeatTable.put("Mumbai", "IT", 60);
universityCourseSeatTable.put("Harvard", "Electrical", 60);
universityCourseSeatTable.put("Harvard", "IT", 120);
final Map<String, Integer> courseSeatMap = universityCourseSeatTable.row("Mumbai");
assertThat(courseSeatMap).hasSize(2);
assertThat(courseSeatMap.get("IT")).isEqualTo(60);
assertThat(courseSeatMap.get("Chemical")).isEqualTo(120);
}
@Test
public void givenTable_whenRowKeySet_returnsSuccessfully() {
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
universityCourseSeatTable.put("Mumbai", "IT", 60);
universityCourseSeatTable.put("Harvard", "Electrical", 60);
universityCourseSeatTable.put("Harvard", "IT", 120);
final Set<String> universitySet = universityCourseSeatTable.rowKeySet();
assertThat(universitySet).hasSize(2);
}
@Test
public void givenTable_whenColKeySet_returnsSuccessfully() {
final Table<String, String, Integer> universityCourseSeatTable = HashBasedTable.create();
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
universityCourseSeatTable.put("Mumbai", "IT", 60);
universityCourseSeatTable.put("Harvard", "Electrical", 60);
universityCourseSeatTable.put("Harvard", "IT", 120);
final Set<String> courseSet = universityCourseSeatTable.columnKeySet();
assertThat(courseSet).hasSize(3);
}
@Test
public void givenTreeTable_whenGet_returnsSuccessfully() {
final Table<String, String, Integer> universityCourseSeatTable = TreeBasedTable.create();
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
universityCourseSeatTable.put("Mumbai", "IT", 60);
universityCourseSeatTable.put("Harvard", "Electrical", 60);
universityCourseSeatTable.put("Harvard", "IT", 120);
final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
assertThat(seatCount).isEqualTo(60);
}
@Test
public void givenImmutableTable_whenGet_returnsSuccessfully() {
final Table<String, String, Integer> universityCourseSeatTable = ImmutableTable.<String, String, Integer> builder()
.put("Mumbai", "Chemical", 120)
.put("Mumbai", "IT", 60)
.put("Harvard", "Electrical", 60)
.put("Harvard", "IT", 120)
.build();
final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
assertThat(seatCount).isEqualTo(60);
}
@Test
public void givenArrayTable_whenGet_returnsSuccessfully() {
final List<String> universityRowTable = Lists.newArrayList("Mumbai", "Harvard");
final List<String> courseColumnTables = Lists.newArrayList("Chemical", "IT", "Electrical");
final Table<String, String, Integer> universityCourseSeatTable = ArrayTable.create(universityRowTable, courseColumnTables);
universityCourseSeatTable.put("Mumbai", "Chemical", 120);
universityCourseSeatTable.put("Mumbai", "IT", 60);
universityCourseSeatTable.put("Harvard", "Electrical", 60);
universityCourseSeatTable.put("Harvard", "IT", 120);
final int seatCount = universityCourseSeatTable.get("Mumbai", "IT");
assertThat(seatCount).isEqualTo(60);
}
}
@@ -0,0 +1,104 @@
package com.baeldung.hamcrest;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.emptyIterable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.hamcrest.Matchers;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class HamcrestExamplesUnitTest {
// tests
@Test
public final void whenVerifyingSingleElementIsPartOfCollection_thenCorrect() {
final List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasItem("cd"));
assertThat(collection, not(hasItem("zz")));
}
@Test
public final void whenVerifyingMultipleElementsArePartOfCollection_thenCorrect1() {
final List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasItems("ef", "cd"));
}
@Test
public final void whenVerifyingMultipleElementsArePartOfCollectionInStrictOrder_thenCorrect2() {
final List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, contains("ab", "cd", "ef"));
}
@Test
public final void whenVerifyingMultipleElementsArePartOfCollectionInAnyOrder_thenCorrect2() {
final List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, containsInAnyOrder("cd", "ab", "ef"));
}
@Test
public final void givenCollectionIsEmpty_whenChecking_thenEmpty() {
final List<String> collection = Lists.newArrayList();
assertThat(collection, empty());
}
@Test
public final void givenIterableIsEmpty_whenChecking_thenEmpty() {
final Iterable<String> collection = Lists.newArrayList();
assertThat(collection, emptyIterable());
}
@Test
public final void givenCollectionIsNotEmpty_whenChecking_thenNotEmpty() {
final List<String> collection = Lists.newArrayList("a");
assertThat(collection, not(empty()));
}
@Test
public final void givenMapIsEmpty_whenChecking_thenEmpty() {
final Map<String, String> collection = Maps.newHashMap();
assertThat(collection, equalTo(Collections.EMPTY_MAP));
}
@Test
public final void givenArrayIsEmpty_whenChecking_thenEmpty() {
final String[] array = new String[] { "ab" };
assertThat(array, not(emptyArray()));
}
@Test
public final void whenCollectionSizeIsChecked_thenCorrect() {
final List<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, hasSize(3));
}
@Test
public final void whenIterableSizeIsChecked_thenCorrect() {
final Iterable<String> collection = Lists.newArrayList("ab", "cd", "ef");
assertThat(collection, Matchers.<String> iterableWithSize(3));
}
@Test
public final void whenCheckingConditionOverEachItem_thenCorrect() {
final List<Integer> collection = Lists.newArrayList(15, 20, 25, 30);
assertThat(collection, everyItem(greaterThan(10)));
}
}
@@ -0,0 +1 @@
John Jane Adam Tom
@@ -0,0 +1 @@
Hello world
@@ -0,0 +1 @@
Test
@@ -0,0 +1,4 @@
John
Jane
Adam
Tom
@@ -0,0 +1 @@
Hello world
Binary file not shown.