Split or move libraries-apache-commons module (#7873)
This commit is contained in:
committed by
Josh Cummings
parent
2a6a8024cd
commit
eb6ced2100
13
libraries-apache-commons-collections/README.md
Normal file
13
libraries-apache-commons-collections/README.md
Normal file
@@ -0,0 +1,13 @@
|
||||
## Apache Commons Collections
|
||||
|
||||
This module contains articles about Apache Commons Collections
|
||||
|
||||
### Relevant articles
|
||||
|
||||
- [Apache Commons Collections SetUtils](https://www.baeldung.com/apache-commons-setutils)
|
||||
- [Apache Commons Collections OrderedMap](https://www.baeldung.com/apache-commons-ordered-map)
|
||||
- [Guide to Apache Commons CircularFifoQueue](https://www.baeldung.com/commons-circular-fifo-queue)
|
||||
- [Apache Commons Collections Bag](https://www.baeldung.com/apache-commons-bag)
|
||||
- [A Guide to Apache Commons Collections CollectionUtils](https://www.baeldung.com/apache-commons-collection-utils)
|
||||
- [Apache Commons Collections BidiMap](https://www.baeldung.com/commons-collections-bidi-map)
|
||||
- [Apache Commons Collections MapUtils](https://www.baeldung.com/apache-commons-map-utils)
|
||||
40
libraries-apache-commons-collections/pom.xml
Normal file
40
libraries-apache-commons-collections/pom.xml
Normal file
@@ -0,0 +1,40 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>libraries-apache-commons-collections</artifactId>
|
||||
<name>libraries-apache-commons-collections</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons.collections.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>java-hamcrest</artifactId>
|
||||
<version>${org.hamcrest.java-hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<commons.collections.version>4.1</commons.collections.version>
|
||||
<assertj.version>3.6.2</assertj.version>
|
||||
<org.hamcrest.java-hamcrest.version>2.0.0.0</org.hamcrest.java-hamcrest.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.commons.collections.collectionutils;
|
||||
|
||||
public class Address {
|
||||
|
||||
private String locality;
|
||||
private String city;
|
||||
private String zip;
|
||||
|
||||
public String getLocality() {
|
||||
return locality;
|
||||
}
|
||||
|
||||
public void setLocality(String locality) {
|
||||
this.locality = locality;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getZip() {
|
||||
return zip;
|
||||
}
|
||||
|
||||
public void setZip(String zip) {
|
||||
this.zip = zip;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("Address [locality=").append(locality).append(", city=").append(city).append(", zip=").append(zip).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public Address(String locality, String city, String zip) {
|
||||
super();
|
||||
this.locality = locality;
|
||||
this.city = city;
|
||||
this.zip = zip;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.baeldung.commons.collections.collectionutils;
|
||||
|
||||
public class Customer implements Comparable<Customer> {
|
||||
|
||||
private Integer id;
|
||||
private String name;
|
||||
private Long phone;
|
||||
private String locality;
|
||||
private String city;
|
||||
private String zip;
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getPhone() {
|
||||
return phone;
|
||||
}
|
||||
|
||||
public void setPhone(Long phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
public String getLocality() {
|
||||
return locality;
|
||||
}
|
||||
|
||||
public void setLocality(String locality) {
|
||||
this.locality = locality;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getZip() {
|
||||
return zip;
|
||||
}
|
||||
|
||||
public void setZip(String zip) {
|
||||
this.zip = zip;
|
||||
}
|
||||
|
||||
public Customer(Integer id, String name, Long phone, String locality, String city, String zip) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.phone = phone;
|
||||
this.locality = locality;
|
||||
this.city = city;
|
||||
this.zip = zip;
|
||||
}
|
||||
|
||||
public Customer(Integer id, String name, Long phone) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.phone = phone;
|
||||
}
|
||||
|
||||
public Customer(String name) {
|
||||
super();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Customer other = (Customer) obj;
|
||||
if (name == null) {
|
||||
if (other.name != null)
|
||||
return false;
|
||||
} else if (!name.equals(other.name))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public int compareTo(Customer o) {
|
||||
return this.name.compareTo(o.getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("Customer [id=").append(id).append(", name=").append(name).append(", phone=").append(phone).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.baeldung.commons.collections;
|
||||
|
||||
import org.apache.commons.collections4.Bag;
|
||||
import org.apache.commons.collections4.SortedBag;
|
||||
import org.apache.commons.collections4.bag.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.core.Is.is;
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
|
||||
public class BagUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMultipleCopies_whenAdded_theCountIsKept() {
|
||||
Bag<Integer> bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
|
||||
|
||||
assertThat(bag.getCount(1), equalTo(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() {
|
||||
Collection<Integer> collection = new ArrayList<>();
|
||||
|
||||
// Collection contract defines that add() should return true
|
||||
assertThat(collection.add(9), is(true));
|
||||
|
||||
// Even when element is already in the collection
|
||||
collection.add(1);
|
||||
assertThat(collection.add(1), is(true));
|
||||
|
||||
Bag<Integer> bag = new HashBag<>();
|
||||
|
||||
// Bag returns true on adding a new element
|
||||
assertThat(bag.add(9), is(true));
|
||||
|
||||
bag.add(1);
|
||||
// But breaks the contract with false when it has to increment the count
|
||||
assertThat(bag.add(1), is(not(true)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() {
|
||||
Bag<Integer> bag = CollectionBag.collectionBag(new HashBag<>());
|
||||
|
||||
bag.add(1);
|
||||
// This time the behavior is compliant to the Java Collection
|
||||
assertThat(bag.add(1), is((true)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() {
|
||||
Bag<Integer> bag = new HashBag<>();
|
||||
|
||||
// Adding 1 for 5 times
|
||||
bag.add(1, 5);
|
||||
assertThat(bag.getCount(1), equalTo(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultipleCopies_whenRemove_allAreRemoved() {
|
||||
Bag<Integer> bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
|
||||
|
||||
// From 3 we delete 1, 2 remain
|
||||
bag.remove(3, 1);
|
||||
assertThat(bag.getCount(3), equalTo(2));
|
||||
|
||||
// From 2 we delete all
|
||||
bag.remove(1);
|
||||
assertThat(bag.getCount(1), equalTo(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTree_whenDuplicateElementsAdded_thenSort() {
|
||||
TreeBag<Integer> bag = new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }));
|
||||
|
||||
assertThat(bag.first(), equalTo(1));
|
||||
assertThat(bag.getCount(bag.first()), equalTo(2));
|
||||
assertThat(bag.last(), equalTo(7));
|
||||
assertThat(bag.getCount(bag.last()), equalTo(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() {
|
||||
SortedBag<Integer> bag = CollectionSortedBag.collectionSortedBag(new TreeBag<>());
|
||||
|
||||
bag.add(1);
|
||||
assertThat(bag.add(1), is((true)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSortedBag_whenDuplicateElementsAdded_thenSort() {
|
||||
SynchronizedSortedBag<Integer> bag = SynchronizedSortedBag.synchronizedSortedBag(new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })));
|
||||
|
||||
assertThat(bag.first(), equalTo(1));
|
||||
assertThat(bag.getCount(bag.first()), equalTo(2));
|
||||
assertThat(bag.last(), equalTo(7));
|
||||
assertThat(bag.getCount(bag.last()), equalTo(3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.commons.collections;
|
||||
|
||||
import org.apache.commons.collections4.BidiMap;
|
||||
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class BidiMapUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenKeyValue_whenPut_thenAddEntryToMap() {
|
||||
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value2");
|
||||
assertEquals(map.size(), 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInverseBidiMap_thenInverseKeyValue() {
|
||||
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value2");
|
||||
BidiMap<String, String> rMap = map.inverseBidiMap();
|
||||
assertTrue(rMap.containsKey("value1") && rMap.containsKey("value2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValue_whenRemoveValue_thenRemoveMatchingMapEntry() {
|
||||
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value2");
|
||||
map.removeValue("value2");
|
||||
assertFalse(map.containsKey("key2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValue_whenGetKey_thenMappedKey() {
|
||||
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||
map.put("key1", "value1");
|
||||
assertEquals(map.getKey("value1"), "key1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenKeyValue_whenAddValue_thenReplaceFirstKey() {
|
||||
BidiMap<String, String> map = new DualHashBidiMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key2", "value1");
|
||||
assertEquals(map.size(), 1);
|
||||
assertFalse(map.containsKey("key1"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.baeldung.commons.collections;
|
||||
|
||||
import org.apache.commons.collections4.MapUtils;
|
||||
import org.apache.commons.collections4.PredicateUtils;
|
||||
import org.apache.commons.collections4.TransformerUtils;
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.collection.IsMapContaining.hasEntry;
|
||||
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
|
||||
import static org.hamcrest.collection.IsMapWithSize.anEmptyMap;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class MapUtilsUnitTest {
|
||||
|
||||
private String[][] color2DArray = new String[][] { { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } };
|
||||
private String[] color1DArray = new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF" };
|
||||
private Map<String, String> colorMap;
|
||||
|
||||
@Before
|
||||
public void createMap() {
|
||||
this.colorMap = MapUtils.putAll(new HashMap<String, String>(), this.color2DArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateMapFrom2DArray_theMapIsCreated() {
|
||||
this.colorMap = MapUtils.putAll(new HashMap<String, String>(), this.color2DArray);
|
||||
|
||||
assertThat(this.colorMap, is(aMapWithSize(this.color2DArray.length)));
|
||||
|
||||
assertThat(this.colorMap, hasEntry("RED", "#FF0000"));
|
||||
assertThat(this.colorMap, hasEntry("GREEN", "#00FF00"));
|
||||
assertThat(this.colorMap, hasEntry("BLUE", "#0000FF"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateMapFrom1DArray_theMapIsCreated() {
|
||||
this.colorMap = MapUtils.putAll(new HashMap<String, String>(), this.color1DArray);
|
||||
|
||||
assertThat(this.colorMap, is(aMapWithSize(this.color1DArray.length / 2)));
|
||||
|
||||
assertThat(this.colorMap, hasEntry("RED", "#FF0000"));
|
||||
assertThat(this.colorMap, hasEntry("GREEN", "#00FF00"));
|
||||
assertThat(this.colorMap, hasEntry("BLUE", "#0000FF"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVerbosePrintMap_thenMustPrintFormattedMap() {
|
||||
MapUtils.verbosePrint(System.out, "Optional Label", this.colorMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetKeyNotPresent_thenMustReturnDefaultValue() {
|
||||
String defaultColorStr = "COLOR_NOT_FOUND";
|
||||
String color = MapUtils.getString(this.colorMap, "BLACK", defaultColorStr);
|
||||
|
||||
assertEquals(color, defaultColorStr);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetOnNullMap_thenMustReturnDefaultValue() {
|
||||
String defaultColorStr = "COLOR_NOT_FOUND";
|
||||
String color = MapUtils.getString(null, "RED", defaultColorStr);
|
||||
|
||||
assertEquals(color, defaultColorStr);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInvertMap_thenMustReturnInvertedMap() {
|
||||
Map<String, String> invColorMap = MapUtils.invertMap(this.colorMap);
|
||||
|
||||
int size = invColorMap.size();
|
||||
Assertions.assertThat(invColorMap).hasSameSizeAs(colorMap).containsKeys(this.colorMap.values().toArray(new String[size])).containsValues(this.colorMap.keySet().toArray(new String[size]));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() {
|
||||
Map<String, String> rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll(new HashMap<String, String>(), this.color1DArray));
|
||||
|
||||
rgbMap.put("ORANGE", "#FFA500");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() {
|
||||
Map<String, String> uniqValuesMap = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate());
|
||||
|
||||
uniqValuesMap.put("NEW_RED", "#FF0000");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateLazyMap_theMapIsCreated() {
|
||||
Map<Integer, String> intStrMap = MapUtils.lazyMap(new HashMap<Integer, String>(), TransformerUtils.stringValueTransformer());
|
||||
|
||||
assertThat(intStrMap, is(anEmptyMap()));
|
||||
|
||||
intStrMap.get(1);
|
||||
intStrMap.get(2);
|
||||
intStrMap.get(3);
|
||||
|
||||
assertThat(intStrMap, is(aMapWithSize(3)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.commons.collections;
|
||||
|
||||
import org.apache.commons.collections4.SetUtils;
|
||||
import org.apache.commons.collections4.set.TransformedSet;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class SetUtilsUnitTest {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenSetAndPredicate_whenPredicatedSet_thenValidateSet_and_throw_IllegalArgumentException() {
|
||||
Set<String> sourceSet = new HashSet<>();
|
||||
sourceSet.addAll(Arrays.asList("London", "Lagos", "Err Source1"));
|
||||
Set<String> validatingSet = SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L"));
|
||||
validatingSet.add("Err Source2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_whenDifference_thenSetView() {
|
||||
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5));
|
||||
Set<Integer> b = new HashSet<>(Arrays.asList(1, 2));
|
||||
SetUtils.SetView<Integer> result = SetUtils.difference(a, b);
|
||||
assertTrue(result.size() == 1 && result.contains(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_whenUnion_thenUnionResult() {
|
||||
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5));
|
||||
Set<Integer> b = new HashSet<>(Arrays.asList(1, 2));
|
||||
Set<Integer> expected = new HashSet<>(Arrays.asList(1, 2, 5));
|
||||
SetUtils.SetView<Integer> union = SetUtils.union(a, b);
|
||||
assertTrue(SetUtils.isEqualSet(expected, union));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSets_whenIntersection_thenIntersectionResult() {
|
||||
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5));
|
||||
Set<Integer> b = new HashSet<>(Arrays.asList(1, 2));
|
||||
Set<Integer> expected = new HashSet<>(Arrays.asList(1, 2));
|
||||
SetUtils.SetView<Integer> intersect = SetUtils.intersection(a, b);
|
||||
assertTrue(SetUtils.isEqualSet(expected, intersect));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_whenTransformedSet_thenTransformedResult() {
|
||||
Set<Integer> a = SetUtils.transformedSet(new HashSet<>(), (e) -> e * 2);
|
||||
a.add(2);
|
||||
assertEquals(a.toArray()[0], 4);
|
||||
|
||||
Set<Integer> source = new HashSet<>(Arrays.asList(1));
|
||||
Set<Integer> newSet = TransformedSet.transformedSet(source, (e) -> e * 2);
|
||||
assertEquals(newSet.toArray()[0], 2);
|
||||
assertEquals(source.toArray()[0], 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSet_whenDisjunction_thenDisjunctionSet() {
|
||||
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 5));
|
||||
Set<Integer> b = new HashSet<>(Arrays.asList(1, 2, 3));
|
||||
SetUtils.SetView<Integer> result = SetUtils.disjunction(a, b);
|
||||
assertTrue(result.toSet().contains(5) && result.toSet().contains(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSet_when_OrderedSet_thenMaintainElementOrder() {
|
||||
Set<Integer> set = new HashSet<>(Arrays.asList(10, 1, 5));
|
||||
System.out.println("unordered set: " + set);
|
||||
|
||||
Set<Integer> orderedSet = SetUtils.orderedSet(new HashSet<>());
|
||||
orderedSet.addAll(Arrays.asList(10, 1, 5));
|
||||
System.out.println("ordered set = " + orderedSet);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package com.baeldung.commons.collections.circularfifoqueue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.collections4.queue.CircularFifoQueue;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CircularFifoQueueUnitTest {
|
||||
|
||||
private static final int DEFAULT_SIZE = 32;
|
||||
|
||||
private static final int FIXED_SIZE = 5;
|
||||
|
||||
private static final int COLLECTION_SIZE = 7;
|
||||
|
||||
private static final String TEST_COLOR = "Red";
|
||||
|
||||
private static final String TEST_COLOR_BY_INDEX = "Blue";
|
||||
|
||||
@Test
|
||||
public void whenUsingDefualtConstructor_correctSizeQueue() {
|
||||
CircularFifoQueue<String> bits = new CircularFifoQueue<>();
|
||||
|
||||
Assert.assertEquals(DEFAULT_SIZE, bits.maxSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAddElements_whenUsingIntConstructor_correctSizeQueue() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(FIXED_SIZE, colors.maxSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCollectionConstructor_correctSizeQueue() {
|
||||
List<String> days = new ArrayList<>();
|
||||
days.add("Monday");
|
||||
days.add("Tuesday");
|
||||
days.add("Wednesday");
|
||||
days.add("Thursday");
|
||||
days.add("Friday");
|
||||
days.add("Saturday");
|
||||
days.add("Sunday");
|
||||
|
||||
CircularFifoQueue<String> daysOfWeek = new CircularFifoQueue<>(days);
|
||||
|
||||
Assert.assertEquals(COLLECTION_SIZE, daysOfWeek.maxSize());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAddElements_whenGetElement_correctElement() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(TEST_COLOR_BY_INDEX, colors.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAddElements_whenPollElement_correctElement() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(TEST_COLOR, colors.poll());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAddElements_whenPeekQueue_correctElement() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(TEST_COLOR, colors.peek());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAddElements_whenElementQueue_correctElement() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(TEST_COLOR, colors.element());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAddElements_whenRemoveElement_correctElement() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(TEST_COLOR, colors.remove());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFullQueue_whenClearQueue_getIsEmpty() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
colors.clear();
|
||||
|
||||
Assert.assertEquals(true, colors.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFullQueue_whenCheckFull_getIsFull() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
Assert.assertEquals(false, colors.isFull());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFullQueue_whenAddMoreElements_getIsAtFullCapacity() {
|
||||
CircularFifoQueue<String> colors = new CircularFifoQueue<>(5);
|
||||
colors.add("Red");
|
||||
colors.add("Blue");
|
||||
colors.add("Green");
|
||||
colors.offer("White");
|
||||
colors.offer("Black");
|
||||
|
||||
colors.add("Orange");
|
||||
colors.add("Violet");
|
||||
colors.add("Pink");
|
||||
|
||||
Assert.assertEquals(true, colors.isAtFullCapacity());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.baeldung.commons.collections.collectionutils;
|
||||
|
||||
import com.baeldung.commons.collections.collectionutils.Address;
|
||||
import com.baeldung.commons.collections.collectionutils.Customer;
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.apache.commons.collections4.Predicate;
|
||||
import org.apache.commons.collections4.Transformer;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CollectionUtilsGuideUnitTest {
|
||||
|
||||
Customer customer1 = new Customer(1, "Daniel", 123456l, "locality1", "city1", "1234");
|
||||
Customer customer4 = new Customer(4, "Bob", 456789l, "locality4", "city4", "4567");
|
||||
List<Customer> list1, list2, list3, linkedList1;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
Customer customer2 = new Customer(2, "Fredrik", 234567l, "locality2", "city2", "2345");
|
||||
Customer customer3 = new Customer(3, "Kyle", 345678l, "locality3", "city3", "3456");
|
||||
Customer customer5 = new Customer(5, "Cat", 567890l, "locality5", "city5", "5678");
|
||||
Customer customer6 = new Customer(6, "John", 678901l, "locality6", "city6", "6789");
|
||||
|
||||
list1 = Arrays.asList(customer1, customer2, customer3);
|
||||
list2 = Arrays.asList(customer4, customer5, customer6);
|
||||
list3 = Arrays.asList(customer1, customer2);
|
||||
|
||||
linkedList1 = new LinkedList<>(list1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_whenAddIgnoreNull_thenNoNullAdded() {
|
||||
CollectionUtils.addIgnoreNull(list1, null);
|
||||
assertFalse(list1.contains(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSortedLists_whenCollated_thenSorted() {
|
||||
List<Customer> sortedList = CollectionUtils.collate(list1, list2);
|
||||
|
||||
assertEquals(6, sortedList.size());
|
||||
assertTrue(sortedList.get(0).getName().equals("Bob"));
|
||||
assertTrue(sortedList.get(2).getName().equals("Daniel"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfCustomers_whenTransformed_thenListOfAddress() {
|
||||
Collection<Address> addressCol = CollectionUtils.collect(list1, new Transformer<Customer, Address>() {
|
||||
public Address transform(Customer customer) {
|
||||
return new Address(customer.getLocality(), customer.getCity(), customer.getZip());
|
||||
}
|
||||
});
|
||||
|
||||
List<Address> addressList = new ArrayList<>(addressCol);
|
||||
assertTrue(addressList.size() == 3);
|
||||
assertTrue(addressList.get(0).getLocality().equals("locality1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomerList_whenFiltered_thenCorrectSize() {
|
||||
|
||||
boolean isModified = CollectionUtils.filter(linkedList1, new Predicate<Customer>() {
|
||||
public boolean evaluate(Customer customer) {
|
||||
return Arrays.asList("Daniel", "Kyle").contains(customer.getName());
|
||||
}
|
||||
});
|
||||
|
||||
// filterInverse does the opposite. It removes the element from the list if the Predicate returns true
|
||||
// select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection
|
||||
|
||||
assertTrue(isModified && linkedList1.size() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonEmptyList_whenCheckedIsNotEmpty_thenTrue() {
|
||||
List<Customer> emptyList = new ArrayList<>();
|
||||
List<Customer> nullList = null;
|
||||
|
||||
// Very handy at times where we want to check if a collection is not null and not empty too.
|
||||
// isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading
|
||||
assertTrue(CollectionUtils.isNotEmpty(list1));
|
||||
assertTrue(CollectionUtils.isEmpty(nullList));
|
||||
assertTrue(CollectionUtils.isEmpty(emptyList));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCustomerListAndASubcollection_whenChecked_thenTrue() {
|
||||
assertTrue(CollectionUtils.isSubCollection(list3, list1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoLists_whenIntersected_thenCheckSize() {
|
||||
Collection<Customer> intersection = CollectionUtils.intersection(list1, list3);
|
||||
assertTrue(intersection.size() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoLists_whenSubtracted_thenCheckElementNotPresentInA() {
|
||||
Collection<Customer> result = CollectionUtils.subtract(list1, list3);
|
||||
assertFalse(result.contains(customer1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoLists_whenUnioned_thenCheckElementPresentInResult() {
|
||||
Collection<Customer> union = CollectionUtils.union(list1, list2);
|
||||
assertTrue(union.contains(customer1));
|
||||
assertTrue(union.contains(customer4));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package com.baeldung.commons.collections.orderedmap;
|
||||
|
||||
import org.apache.commons.collections4.OrderedMap;
|
||||
import org.apache.commons.collections4.OrderedMapIterator;
|
||||
import org.apache.commons.collections4.map.LinkedMap;
|
||||
import org.apache.commons.collections4.map.ListOrderedMap;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class OrderedMapUnitTest {
|
||||
|
||||
private String[] names = { "Emily", "Mathew", "Rose", "John", "Anna" };
|
||||
private Integer[] ages = { 37, 28, 40, 36, 21 };
|
||||
|
||||
private int RUNNERS_COUNT = names.length;
|
||||
|
||||
private OrderedMap<String, Integer> runnersLinkedMap;
|
||||
private OrderedMap<String, Integer> runnersListOrderedMap;
|
||||
|
||||
@Before
|
||||
public void createRunners() {
|
||||
// First implementation: ListOrderedMap
|
||||
this.runnersListOrderedMap = new ListOrderedMap<>();
|
||||
this.loadOrderedMapOfRunners(this.runnersListOrderedMap);
|
||||
|
||||
// Second implementation: LinkedMap
|
||||
this.runnersLinkedMap = new LinkedMap<>();
|
||||
this.loadOrderedMapOfRunners(this.runnersLinkedMap);
|
||||
}
|
||||
|
||||
private void loadOrderedMapOfRunners(OrderedMap<String, Integer> runners) {
|
||||
for (int i = 0; i < RUNNERS_COUNT; i++) {
|
||||
runners.put(this.names[i], this.ages[i]);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenIteratedWithMapIterator_thenPreservesOrder() {
|
||||
// Tests that the order in map iterator is the same
|
||||
// as defined in the constant arrays of names and ages:
|
||||
|
||||
OrderedMapIterator<String, Integer> runnersIterator = this.runnersLinkedMap.mapIterator();
|
||||
int i = 0;
|
||||
while (runnersIterator.hasNext()) {
|
||||
runnersIterator.next();
|
||||
assertEquals(runnersIterator.getKey(), this.names[i]);
|
||||
assertEquals(runnersIterator.getValue(), this.ages[i]);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenIteratedWithMapIterator_thenPreservesOrder() {
|
||||
// Tests that the order in map iterator is the same
|
||||
// as defined in the constant arrays of names and ages:
|
||||
|
||||
OrderedMapIterator<String, Integer> runnersIterator = this.runnersListOrderedMap.mapIterator();
|
||||
int i = 0;
|
||||
while (runnersIterator.hasNext()) {
|
||||
runnersIterator.next();
|
||||
assertEquals(runnersIterator.getKey(), this.names[i]);
|
||||
assertEquals(runnersIterator.getValue(), this.ages[i]);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenIteratedForwards_thenPreservesOrder() {
|
||||
// Tests that the order in the forward iteration is the same
|
||||
// as defined in the constant arrays of names and ages
|
||||
|
||||
String name = this.runnersLinkedMap.firstKey();
|
||||
int i = 0;
|
||||
while (name != null) {
|
||||
assertEquals(name, this.names[i]);
|
||||
name = this.runnersLinkedMap.nextKey(name);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenIteratedForwards_thenPreservesOrder() {
|
||||
// Tests that the order in the forward iteration is the same
|
||||
// as defined in the constant arrays of names and ages
|
||||
|
||||
String name = this.runnersListOrderedMap.firstKey();
|
||||
int i = 0;
|
||||
while (name != null) {
|
||||
assertEquals(name, this.names[i]);
|
||||
name = this.runnersListOrderedMap.nextKey(name);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenIteratedBackwards_thenPreservesOrder() {
|
||||
// Tests that the order in the backwards iteration is the same
|
||||
// as defined in the constant arrays of names and ages
|
||||
|
||||
String name = this.runnersLinkedMap.lastKey();
|
||||
int i = RUNNERS_COUNT - 1;
|
||||
while (name != null) {
|
||||
assertEquals(name, this.names[i]);
|
||||
name = this.runnersLinkedMap.previousKey(name);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenIteratedBackwards_thenPreservesOrder() {
|
||||
// Tests that the order in the backwards iteration is the same
|
||||
// as defined in the constant arrays of names and ages
|
||||
|
||||
String name = this.runnersListOrderedMap.lastKey();
|
||||
int i = RUNNERS_COUNT - 1;
|
||||
while (name != null) {
|
||||
assertEquals(name, this.names[i]);
|
||||
name = this.runnersListOrderedMap.previousKey(name);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenObjectIsSearched_thenMatchesConstantArray() {
|
||||
assertEquals(ages[4], this.runnersLinkedMap.get("Anna"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenConvertedToList_thenMatchesKeySet() {
|
||||
// Casting the OrderedMap to a LinkedMap we can use asList() method
|
||||
|
||||
LinkedMap<String, Integer> lmap = (LinkedMap<String, Integer>) this.runnersLinkedMap;
|
||||
List<String> listKeys = new ArrayList<>();
|
||||
listKeys.addAll(this.runnersLinkedMap.keySet());
|
||||
List<String> linkedMap = lmap.asList();
|
||||
assertEquals(listKeys, linkedMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenSearchByIndexIsUsed_thenMatchesConstantArray() {
|
||||
LinkedMap<String, Integer> lmap = (LinkedMap<String, Integer>) this.runnersLinkedMap;
|
||||
|
||||
for (int i = 0; i < RUNNERS_COUNT; i++) {
|
||||
// accessed by index:
|
||||
String name = lmap.get(i);
|
||||
assertEquals(name, this.names[i]);
|
||||
|
||||
// index of key concides with position in array
|
||||
assertEquals(lmap.indexOf(this.names[i]), i);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenALinkedMap_whenElementRemoved_thenSizeDecrease() {
|
||||
LinkedMap<String, Integer> lmap = (LinkedMap<String, Integer>) this.runnersLinkedMap;
|
||||
Integer johnAge = lmap.remove("John");// by object
|
||||
assertEquals(johnAge, new Integer(36));
|
||||
assertEquals(lmap.size(), RUNNERS_COUNT - 1);
|
||||
|
||||
Integer emilyAge = lmap.remove(0);// by index
|
||||
assertEquals(emilyAge, new Integer(37));
|
||||
assertEquals(lmap.size(), RUNNERS_COUNT - 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenObjectIsSearched_thenMatchesConstantArray() {
|
||||
assertEquals(ages[4], this.runnersListOrderedMap.get("Anna"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenConvertedToList_thenMatchesKeySet() {
|
||||
ListOrderedMap<String, Integer> lomap = (ListOrderedMap<String, Integer>) this.runnersListOrderedMap;
|
||||
List<String> listKeys = new ArrayList<>();
|
||||
listKeys.addAll(this.runnersListOrderedMap.keySet());
|
||||
List<String> lomapList = lomap.asList();
|
||||
assertEquals(listKeys, lomapList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenSearchByIndexIsUsed_thenMatchesConstantArray() {
|
||||
ListOrderedMap<String, Integer> lomap = (ListOrderedMap<String, Integer>) this.runnersListOrderedMap;
|
||||
|
||||
for (int i = 0; i < RUNNERS_COUNT; i++) {
|
||||
// accessed by index:
|
||||
String name = lomap.get(i);
|
||||
assertEquals(name, this.names[i]);
|
||||
|
||||
// index of key concides with position in array
|
||||
assertEquals(lomap.indexOf(this.names[i]), i);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAListOrderedMap_whenElementRemoved_thenSizeDecrease() {
|
||||
ListOrderedMap<String, Integer> lomap = (ListOrderedMap<String, Integer>) this.runnersListOrderedMap;
|
||||
|
||||
Integer johnAge = lomap.remove("John");// by object
|
||||
|
||||
assertEquals(johnAge, new Integer(36));
|
||||
assertEquals(lomap.size(), RUNNERS_COUNT - 1);
|
||||
|
||||
Integer emilyAge = lomap.remove(0);// by index
|
||||
assertEquals(emilyAge, new Integer(37));
|
||||
assertEquals(lomap.size(), RUNNERS_COUNT - 2);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user