[BAEL-9547] - Splitted guava module and introduced guava-collections module
This commit is contained in:
@@ -1,31 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,316 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.common.base.Predicates;
|
||||
import com.google.common.collect.ArrayListMultimap;
|
||||
import com.google.common.collect.BiMap;
|
||||
import com.google.common.collect.ClassToInstanceMap;
|
||||
import com.google.common.collect.ContiguousSet;
|
||||
import com.google.common.collect.DiscreteDomain;
|
||||
import com.google.common.collect.HashBasedTable;
|
||||
import com.google.common.collect.HashBiMap;
|
||||
import com.google.common.collect.HashMultiset;
|
||||
import com.google.common.collect.ImmutableList;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.collect.ImmutableSortedMap;
|
||||
import com.google.common.collect.Iterables;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.collect.Multimaps;
|
||||
import com.google.common.collect.Multiset;
|
||||
import com.google.common.collect.Multisets;
|
||||
import com.google.common.collect.MutableClassToInstanceMap;
|
||||
import com.google.common.collect.Ordering;
|
||||
import com.google.common.collect.Range;
|
||||
import com.google.common.collect.RangeSet;
|
||||
import com.google.common.collect.Sets;
|
||||
import com.google.common.collect.Table;
|
||||
import com.google.common.collect.Tables;
|
||||
import com.google.common.collect.TreeRangeSet;
|
||||
|
||||
public class GuavaCollectionTypesUnitTest {
|
||||
|
||||
@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"));
|
||||
}
|
||||
|
||||
// sets
|
||||
|
||||
@Test
|
||||
public void whenCalculateUnionOfSets_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
|
||||
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
|
||||
|
||||
final Set<Character> union = Sets.union(first, second);
|
||||
assertThat(union, containsInAnyOrder('a', 'b', 'c', 'd'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculateSetsProduct_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b');
|
||||
final Set<Character> second = ImmutableSet.of('c', 'd');
|
||||
final Set<List<Character>> result = Sets.cartesianProduct(ImmutableList.of(first, second));
|
||||
|
||||
final Function<List<Character>, String> func = new Function<List<Character>, String>() {
|
||||
@Override
|
||||
public final String apply(final List<Character> input) {
|
||||
return Joiner.on(" ").join(input);
|
||||
}
|
||||
};
|
||||
|
||||
final Iterable<String> joined = Iterables.transform(result, func);
|
||||
assertThat(joined, containsInAnyOrder("a c", "a d", "b c", "b d"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingSetIntersection_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
|
||||
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
|
||||
|
||||
final Set<Character> intersection = Sets.intersection(first, second);
|
||||
assertThat(intersection, containsInAnyOrder('b', 'c'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingSetSymmetricDifference_thenCorrect() {
|
||||
final Set<Character> first = ImmutableSet.of('a', 'b', 'c');
|
||||
final Set<Character> second = ImmutableSet.of('b', 'c', 'd');
|
||||
|
||||
final Set<Character> intersection = Sets.symmetricDifference(first, second);
|
||||
assertThat(intersection, containsInAnyOrder('a', 'd'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingPowerSet_thenCorrect() {
|
||||
final Set<Character> chars = ImmutableSet.of('a', 'b');
|
||||
final Set<Set<Character>> result = Sets.powerSet(chars);
|
||||
|
||||
final Set<Character> empty = ImmutableSet.<Character> builder().build();
|
||||
final Set<Character> a = ImmutableSet.of('a');
|
||||
final Set<Character> b = ImmutableSet.of('b');
|
||||
final Set<Character> aB = ImmutableSet.of('a', 'b');
|
||||
|
||||
assertThat(result, contains(empty, a, b, aB));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateRangeOfIntegersSet_thenCreated() {
|
||||
final int start = 10;
|
||||
final int end = 30;
|
||||
final ContiguousSet<Integer> set = ContiguousSet.create(Range.closed(start, end), DiscreteDomain.integers());
|
||||
|
||||
assertEquals(21, set.size());
|
||||
assertEquals(10, set.first().intValue());
|
||||
assertEquals(30, set.last().intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateRangeSet_thenCreated() {
|
||||
final RangeSet<Integer> rangeSet = TreeRangeSet.create();
|
||||
rangeSet.add(Range.closed(1, 10));
|
||||
rangeSet.add(Range.closed(12, 15));
|
||||
|
||||
assertEquals(2, rangeSet.asRanges().size());
|
||||
|
||||
rangeSet.add(Range.closed(10, 12));
|
||||
assertTrue(rangeSet.encloses(Range.closed(1, 15)));
|
||||
assertEquals(1, rangeSet.asRanges().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInsertDuplicatesInMultiSet_thenInserted() {
|
||||
final Multiset<String> names = HashMultiset.create();
|
||||
names.add("John");
|
||||
names.add("Adam", 3);
|
||||
names.add("John");
|
||||
|
||||
assertEquals(2, names.count("John"));
|
||||
names.remove("John");
|
||||
assertEquals(1, names.count("John"));
|
||||
|
||||
assertEquals(3, names.count("Adam"));
|
||||
names.remove("Adam", 2);
|
||||
assertEquals(1, names.count("Adam"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetTopUsingMultiSet_thenCorrect() {
|
||||
final Multiset<String> names = HashMultiset.create();
|
||||
names.add("John");
|
||||
names.add("Adam", 5);
|
||||
names.add("Jane");
|
||||
names.add("Tom", 2);
|
||||
|
||||
final Set<String> sorted = Multisets.copyHighestCountFirst(names).elementSet();
|
||||
final List<String> topTwo = Lists.newArrayList(sorted).subList(0, 2);
|
||||
assertEquals(2, topTwo.size());
|
||||
assertEquals("Adam", topTwo.get(0));
|
||||
assertEquals("Tom", topTwo.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateImmutableMap_thenCreated() {
|
||||
final Map<String, Integer> salary = ImmutableMap.<String, Integer> builder().put("John", 1000).put("Jane", 1500).put("Adam", 2000).put("Tom", 2000).build();
|
||||
|
||||
assertEquals(1000, salary.get("John").intValue());
|
||||
assertEquals(2000, salary.get("Tom").intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseSortedMap_thenKeysAreSorted() {
|
||||
final ImmutableSortedMap<String, Integer> salary = new ImmutableSortedMap.Builder<String, Integer>(Ordering.natural()).put("John", 1000).put("Jane", 1500).put("Adam", 2000).put("Tom", 2000).build();
|
||||
|
||||
assertEquals("Adam", salary.firstKey());
|
||||
assertEquals(2000, salary.lastEntry().getValue().intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateBiMap_thenCreated() {
|
||||
final BiMap<String, Integer> words = HashBiMap.create();
|
||||
words.put("First", 1);
|
||||
words.put("Second", 2);
|
||||
words.put("Third", 3);
|
||||
|
||||
assertEquals(2, words.get("Second").intValue());
|
||||
assertEquals("Third", words.inverse().get(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateMultimap_thenCreated() {
|
||||
final Multimap<String, String> multimap = ArrayListMultimap.create();
|
||||
multimap.put("fruit", "apple");
|
||||
multimap.put("fruit", "banana");
|
||||
multimap.put("pet", "cat");
|
||||
multimap.put("pet", "dog");
|
||||
|
||||
assertThat(multimap.get("fruit"), containsInAnyOrder("apple", "banana"));
|
||||
assertThat(multimap.get("pet"), containsInAnyOrder("cat", "dog"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGroupListUsingMultimap_thenGrouped() {
|
||||
final List<String> names = Lists.newArrayList("John", "Adam", "Tom");
|
||||
final Function<String, Integer> function = new Function<String, Integer>() {
|
||||
@Override
|
||||
public final Integer apply(final String input) {
|
||||
return input.length();
|
||||
}
|
||||
};
|
||||
final Multimap<Integer, String> groups = Multimaps.index(names, function);
|
||||
|
||||
assertThat(groups.get(3), containsInAnyOrder("Tom"));
|
||||
assertThat(groups.get(4), containsInAnyOrder("John", "Adam"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateTable_thenCreated() {
|
||||
final Table<String, String, Integer> distance = HashBasedTable.create();
|
||||
distance.put("London", "Paris", 340);
|
||||
distance.put("New York", "Los Angeles", 3940);
|
||||
distance.put("London", "New York", 5576);
|
||||
|
||||
assertEquals(3940, distance.get("New York", "Los Angeles").intValue());
|
||||
assertThat(distance.columnKeySet(), containsInAnyOrder("Paris", "New York", "Los Angeles"));
|
||||
assertThat(distance.rowKeySet(), containsInAnyOrder("London", "New York"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTransposeTable_thenCorrect() {
|
||||
final Table<String, String, Integer> distance = HashBasedTable.create();
|
||||
distance.put("London", "Paris", 340);
|
||||
distance.put("New York", "Los Angeles", 3940);
|
||||
distance.put("London", "New York", 5576);
|
||||
|
||||
final Table<String, String, Integer> transposed = Tables.transpose(distance);
|
||||
assertThat(transposed.rowKeySet(), containsInAnyOrder("Paris", "New York", "Los Angeles"));
|
||||
assertThat(transposed.columnKeySet(), containsInAnyOrder("London", "New York"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateClassToInstanceMap_thenCreated() {
|
||||
final ClassToInstanceMap<Number> numbers = MutableClassToInstanceMap.create();
|
||||
numbers.putInstance(Integer.class, 1);
|
||||
numbers.putInstance(Double.class, 1.5);
|
||||
|
||||
assertEquals(1, numbers.get(Integer.class));
|
||||
assertEquals(1.5, numbers.get(Double.class));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
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"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
import java.util.AbstractMap;
|
||||
import java.util.AbstractSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.WeakHashMap;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
|
||||
public class GuavaMapFromSet<K, V> extends AbstractMap<K, V> {
|
||||
|
||||
private class SingleEntry implements Entry<K, V> {
|
||||
private K key;
|
||||
|
||||
public SingleEntry(K key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public K getKey() {
|
||||
return this.key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public V getValue() {
|
||||
V value = GuavaMapFromSet.this.cache.get(this.key);
|
||||
if (value == null) {
|
||||
value = GuavaMapFromSet.this.function.apply(this.key);
|
||||
GuavaMapFromSet.this.cache.put(this.key, value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public V setValue(V value) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
||||
private class MyEntrySet extends AbstractSet<Entry<K, V>> {
|
||||
|
||||
public class EntryIterator implements Iterator<Entry<K, V>> {
|
||||
private Iterator<K> inner;
|
||||
|
||||
public EntryIterator() {
|
||||
this.inner = MyEntrySet.this.keys.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return this.inner.hasNext();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map.Entry<K, V> next() {
|
||||
K key = this.inner.next();
|
||||
return new SingleEntry(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
|
||||
private Set<K> keys;
|
||||
|
||||
public MyEntrySet(Set<K> keys) {
|
||||
this.keys = keys;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<Map.Entry<K, V>> iterator() {
|
||||
return new EntryIterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return this.keys.size();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private WeakHashMap<K, V> cache;
|
||||
private Set<Entry<K, V>> entries;
|
||||
private Function<? super K, ? extends V> function;
|
||||
|
||||
public GuavaMapFromSet(Set<K> keys, Function<? super K, ? extends V> function) {
|
||||
this.function = function;
|
||||
this.cache = new WeakHashMap<K, V>();
|
||||
this.entries = new MyEntrySet(keys);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Map.Entry<K, V>> entrySet() {
|
||||
return this.entries;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.base.Function;
|
||||
|
||||
public class GuavaMapFromSetUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStringSet_whenMapsToElementLength_thenCorrect() {
|
||||
Function<Integer, String> function = new Function<Integer, String>() {
|
||||
@Override
|
||||
public String apply(Integer from) {
|
||||
return Integer.toBinaryString(from);
|
||||
}
|
||||
};
|
||||
Set<Integer> set = new TreeSet<>(Arrays.asList(32, 64, 128));
|
||||
Map<Integer, String> map = new GuavaMapFromSet<Integer, String>(set, function);
|
||||
assertTrue(map.get(32).equals("100000")
|
||||
&& map.get(64).equals("1000000")
|
||||
&& map.get(128).equals("10000000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIntSet_whenMapsToElementBinaryValue_thenCorrect() {
|
||||
Function<String, Integer> function = new Function<String, Integer>() {
|
||||
|
||||
@Override
|
||||
public Integer apply(String from) {
|
||||
return from.length();
|
||||
}
|
||||
};
|
||||
Set<String> set = new TreeSet<>(Arrays.asList(
|
||||
"four", "three", "twelve"));
|
||||
Map<String, Integer> map = new GuavaMapFromSet<String, Integer>(set,
|
||||
function);
|
||||
assertTrue(map.get("four") == 4 && map.get("three") == 5
|
||||
&& map.get("twelve") == 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_whenNewSetElementAddedAndMappedLive_thenCorrect() {
|
||||
Function<String, Integer> function = new Function<String, Integer>() {
|
||||
|
||||
@Override
|
||||
public Integer apply(String from) {
|
||||
return from.length();
|
||||
}
|
||||
};
|
||||
Set<String> set = new TreeSet<>(Arrays.asList(
|
||||
"four", "three", "twelve"));
|
||||
Map<String, Integer> map = new GuavaMapFromSet<String, Integer>(set,
|
||||
function);
|
||||
set.add("one");
|
||||
assertTrue(map.get("one") == 3 && map.size() == 4);
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.Map;
|
||||
import org.junit.Test;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
public class GuavaMapInitializeUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenKeyValuesShoudInitializeMap() {
|
||||
Map<String, String> articles = ImmutableMap.of("Title", "My New Article", "Title2", "Second Article");
|
||||
|
||||
assertThat(articles.get("Title"), equalTo("My New Article"));
|
||||
assertThat(articles.get("Title2"), equalTo("Second Article"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenKeyValuesShouldCreateMutableMap() {
|
||||
Map<String, String> articles = Maps.newHashMap(ImmutableMap.of("Title", "My New Article", "Title2", "Second Article"));
|
||||
|
||||
assertThat(articles.get("Title"), equalTo("My New Article"));
|
||||
assertThat(articles.get("Title2"), equalTo("Second Article"));
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
import com.google.common.collect.ArrayListMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
|
||||
public class GuavaMultiMapUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMap_whenAddTwoValuesForSameKey_shouldOverridePreviousKey() {
|
||||
//given
|
||||
String key = "a-key";
|
||||
Map<String, String> map = new LinkedHashMap<>();
|
||||
|
||||
//when
|
||||
map.put(key, "firstValue");
|
||||
map.put(key, "secondValue");
|
||||
|
||||
//then
|
||||
assertEquals(1, map.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiMap_whenAddTwoValuesForSameKey_shouldHaveTwoEntriesInMap() {
|
||||
//given
|
||||
String key = "a-key";
|
||||
Multimap<String, String> map = ArrayListMultimap.create();
|
||||
|
||||
//when
|
||||
map.put(key, "firstValue");
|
||||
map.put(key, "secondValue");
|
||||
|
||||
//then
|
||||
assertEquals(2, map.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMapOfListValues_whenAddTwoValuesForSameKey_shouldHaveTwoElementsInList() {
|
||||
//given
|
||||
String key = "a-key";
|
||||
Map<String, List<String>> map = new LinkedHashMap<>();
|
||||
|
||||
//when
|
||||
List<String> values = map.get(key);
|
||||
if(values == null){
|
||||
values = new LinkedList<>();
|
||||
values.add("firstValue");
|
||||
values.add("secondValue");
|
||||
}
|
||||
map.put(key, values);
|
||||
|
||||
//then
|
||||
assertEquals(1, map.size());
|
||||
}
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import java.util.Map;
|
||||
import org.junit.Test;
|
||||
import com.google.common.collect.ImmutableRangeMap;
|
||||
import com.google.common.collect.Range;
|
||||
import com.google.common.collect.RangeMap;
|
||||
import com.google.common.collect.TreeRangeMap;
|
||||
|
||||
public class GuavaRangeMapUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenQueryWithinRange_returnsSucessfully() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = TreeRangeMap.create();
|
||||
|
||||
experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President");
|
||||
experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director");
|
||||
experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director");
|
||||
|
||||
assertEquals("Vice President", experienceRangeDesignationMap.get(6));
|
||||
assertEquals("Executive Director", experienceRangeDesignationMap.get(15));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenQueryOutsideRange_returnsNull() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = TreeRangeMap.create();
|
||||
|
||||
experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President");
|
||||
experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director");
|
||||
experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director");
|
||||
|
||||
assertNull(experienceRangeDesignationMap.get(31));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenRemoveRangeIsCalled_removesSucessfully() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = TreeRangeMap.create();
|
||||
|
||||
experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President");
|
||||
experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director");
|
||||
experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director");
|
||||
experienceRangeDesignationMap.remove(Range.closed(8, 15));
|
||||
experienceRangeDesignationMap.remove(Range.closed(20, 26));
|
||||
|
||||
assertNull(experienceRangeDesignationMap.get(9));
|
||||
assertEquals("Managing Director", experienceRangeDesignationMap.get(16));
|
||||
assertEquals("Managing Director", experienceRangeDesignationMap.get(30));
|
||||
assertNull(experienceRangeDesignationMap.get(25));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenSpanIsCalled_returnsSucessfully() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = TreeRangeMap.create();
|
||||
|
||||
experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President");
|
||||
experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director");
|
||||
experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director");
|
||||
final Range<Integer> experienceSpan = experienceRangeDesignationMap.span();
|
||||
|
||||
assertEquals(0, experienceSpan.lowerEndpoint().intValue());
|
||||
assertEquals(30, experienceSpan.upperEndpoint().intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenGetEntryIsCalled_returnsEntrySucessfully() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = TreeRangeMap.create();
|
||||
|
||||
experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President");
|
||||
experienceRangeDesignationMap.put(Range.closed(9, 15), "Executive Director");
|
||||
experienceRangeDesignationMap.put(Range.closed(20, 30), "Managing Director");
|
||||
final Map.Entry<Range<Integer>, String> experiencEntry = experienceRangeDesignationMap.getEntry(10);
|
||||
|
||||
assertEquals(Range.closed(9, 15), experiencEntry.getKey());
|
||||
assertEquals("Executive Director", experiencEntry.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeMap_whenSubRangeMapIsCalled_returnsSubRangeSucessfully() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = TreeRangeMap.create();
|
||||
|
||||
experienceRangeDesignationMap.put(Range.closed(0, 2), "Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(3, 5), "Senior Associate");
|
||||
experienceRangeDesignationMap.put(Range.closed(6, 8), "Vice President");
|
||||
experienceRangeDesignationMap.put(Range.closed(8, 15), "Executive Director");
|
||||
experienceRangeDesignationMap.put(Range.closed(16, 30), "Managing Director");
|
||||
final RangeMap<Integer, String> experiencedSubRangeDesignationMap = experienceRangeDesignationMap.subRangeMap(Range.closed(4, 14));
|
||||
|
||||
assertNull(experiencedSubRangeDesignationMap.get(3));
|
||||
assertEquals("Executive Director", experiencedSubRangeDesignationMap.get(14));
|
||||
assertEquals("Vice President", experiencedSubRangeDesignationMap.get(7));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImmutableRangeMap_whenQueryWithinRange_returnsSucessfully() {
|
||||
final RangeMap<Integer, String> experienceRangeDesignationMap = ImmutableRangeMap.<Integer, String> builder()
|
||||
.put(Range.closed(0, 2), "Associate")
|
||||
.put(Range.closed(3, 5), "Senior Associate")
|
||||
.put(Range.closed(6, 8), "Vice President")
|
||||
.put(Range.closed(9, 15), "Executive Director")
|
||||
.put(Range.closed(16, 30), "Managing Director").build();
|
||||
|
||||
assertEquals("Vice President", experienceRangeDesignationMap.get(6));
|
||||
assertEquals("Executive Director", experienceRangeDesignationMap.get(15));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenImmutableRangeMap_whenRangeOverlaps_ThrowsException() {
|
||||
ImmutableRangeMap.<Integer, String> builder()
|
||||
.put(Range.closed(0, 2), "Associate")
|
||||
.put(Range.closed(3, 5), "Senior Associate")
|
||||
.put(Range.closed(6, 8), "Vice President")
|
||||
.put(Range.closed(8, 15), "Executive Director")
|
||||
.put(Range.closed(16, 30), "Managing Director").build();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import org.junit.Test;
|
||||
import com.google.common.collect.ImmutableRangeSet;
|
||||
import com.google.common.collect.Range;
|
||||
import com.google.common.collect.RangeSet;
|
||||
import com.google.common.collect.TreeRangeSet;
|
||||
|
||||
public class GuavaRangeSetUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenQueryWithinRange_returnsSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 5));
|
||||
numberRangeSet.add(Range.closed(6, 8));
|
||||
|
||||
assertTrue(numberRangeSet.contains(1));
|
||||
assertFalse(numberRangeSet.contains(9));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenEnclosesWithinRange_returnsSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 10));
|
||||
numberRangeSet.add(Range.closed(15, 18));
|
||||
|
||||
assertTrue(numberRangeSet.encloses(Range.closed(4, 5)));
|
||||
assertFalse(numberRangeSet.encloses(Range.closed(4, 11)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenComplementIsCalled_returnsSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 5));
|
||||
numberRangeSet.add(Range.closed(6, 8));
|
||||
final RangeSet<Integer> numberRangeComplementSet = numberRangeSet.complement();
|
||||
|
||||
assertTrue(numberRangeComplementSet.contains(-1000));
|
||||
assertFalse(numberRangeComplementSet.contains(2));
|
||||
assertFalse(numberRangeComplementSet.contains(3));
|
||||
assertTrue(numberRangeComplementSet.contains(1000));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenIntersectsWithinRange_returnsSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 10));
|
||||
numberRangeSet.add(Range.closed(15, 18));
|
||||
|
||||
assertTrue(numberRangeSet.intersects(Range.closed(4, 17)));
|
||||
assertFalse(numberRangeSet.intersects(Range.closed(19, 200)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenRemoveRangeIsCalled_removesSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 5));
|
||||
numberRangeSet.add(Range.closed(6, 8));
|
||||
numberRangeSet.add(Range.closed(9, 15));
|
||||
numberRangeSet.remove(Range.closed(3, 5));
|
||||
numberRangeSet.remove(Range.closed(7, 10));
|
||||
|
||||
assertTrue(numberRangeSet.contains(1));
|
||||
assertFalse(numberRangeSet.contains(9));
|
||||
assertTrue(numberRangeSet.contains(12));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenSpanIsCalled_returnsSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 5));
|
||||
numberRangeSet.add(Range.closed(6, 8));
|
||||
final Range<Integer> experienceSpan = numberRangeSet.span();
|
||||
|
||||
assertEquals(0, experienceSpan.lowerEndpoint().intValue());
|
||||
assertEquals(8, experienceSpan.upperEndpoint().intValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRangeSet_whenSubRangeSetIsCalled_returnsSubRangeSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = TreeRangeSet.create();
|
||||
|
||||
numberRangeSet.add(Range.closed(0, 2));
|
||||
numberRangeSet.add(Range.closed(3, 5));
|
||||
numberRangeSet.add(Range.closed(6, 8));
|
||||
final RangeSet<Integer> numberSubRangeSet = numberRangeSet.subRangeSet(Range.closed(4, 14));
|
||||
|
||||
assertFalse(numberSubRangeSet.contains(3));
|
||||
assertFalse(numberSubRangeSet.contains(14));
|
||||
assertTrue(numberSubRangeSet.contains(7));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenImmutableRangeSet_whenQueryWithinRange_returnsSucessfully() {
|
||||
final RangeSet<Integer> numberRangeSet = ImmutableRangeSet.<Integer> builder()
|
||||
.add(Range.closed(0, 2))
|
||||
.add(Range.closed(3, 5))
|
||||
.add(Range.closed(6, 8)).build();
|
||||
|
||||
assertTrue(numberRangeSet.contains(6));
|
||||
assertFalse(numberRangeSet.contains(15));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenImmutableRangeMap_whenRangeOverlaps_ThrowsException() {
|
||||
ImmutableRangeSet.<Integer> builder()
|
||||
.add(Range.closed(0, 2))
|
||||
.add(Range.closed(3, 5))
|
||||
.add(Range.closed(5, 8)).build();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package org.baeldung.guava;
|
||||
|
||||
|
||||
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 +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package org.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)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package org.baeldung.java;
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package org.baeldung.java;
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package org.baeldung.java;
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user