[BAEL-9550] - Moved articles and codes from core-java-collections module to java-collections-convversions and java-collections-maps module
This commit is contained in:
@@ -1,60 +0,0 @@
|
||||
package com.baeldung.collection;
|
||||
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class WhenComparingTreeMapVsHashMap {
|
||||
|
||||
@Test
|
||||
public void whenInsertObjectsTreeMap_thenNaturalOrder() {
|
||||
Map<Integer, String> treemap = new TreeMap<>();
|
||||
treemap.put(3, "TreeMap");
|
||||
treemap.put(2, "vs");
|
||||
treemap.put(1, "HashMap");
|
||||
Assert.assertThat(treemap.keySet(), Matchers.contains(1, 2, 3));
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void whenInsertNullInTreeMap_thenException() {
|
||||
Map<Integer, String> treemap = new TreeMap<>();
|
||||
treemap.put(null, "NullPointerException");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInsertObjectsHashMap_thenRandomOrder() {
|
||||
Map<Integer, String> hashmap = new HashMap<>();
|
||||
hashmap.put(3, "TreeMap");
|
||||
hashmap.put(2, "vs");
|
||||
hashmap.put(1, "HashMap");
|
||||
Assert.assertThat(hashmap.keySet(), Matchers.containsInAnyOrder(1, 2, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInsertNullInHashMap_thenInsertsNull() {
|
||||
Map<Integer, String> hashmap = new HashMap<>();
|
||||
hashmap.put(null, null);
|
||||
Assert.assertNull(hashmap.get(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHashMapAndTreeMap_whenputDuplicates_thenOnlyUnique() {
|
||||
Map<Integer, String> treeMap = new HashMap<>();
|
||||
treeMap.put(1, "Baeldung");
|
||||
treeMap.put(1, "Baeldung");
|
||||
|
||||
Assert.assertTrue(treeMap.size() == 1);
|
||||
|
||||
Map<Integer, String> treeMap2 = new TreeMap<>();
|
||||
treeMap2.put(1, "Baeldung");
|
||||
treeMap2.put(1, "Baeldung");
|
||||
|
||||
Assert.assertTrue(treeMap2.size() == 1);
|
||||
}
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
package com.baeldung.convertcollectiontoarraylist;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import static java.util.stream.Collectors.toCollection;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author chris
|
||||
*/
|
||||
public class FooUnitTest {
|
||||
private static Collection<Foo> srcCollection = new HashSet<>();
|
||||
|
||||
public FooUnitTest() {
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpClass() {
|
||||
int i = 0;
|
||||
Foo john = new Foo(i++, "John", null);
|
||||
Foo mary = new Foo(i++, "Mary", null);
|
||||
Foo sam = new Foo(i++, "Sam", john);
|
||||
Foo alice = new Foo(i++, "Alice", john);
|
||||
Foo buffy = new Foo(i++, "Buffy", sam);
|
||||
srcCollection.add(john);
|
||||
srcCollection.add(mary);
|
||||
srcCollection.add(sam);
|
||||
srcCollection.add(alice);
|
||||
srcCollection.add(buffy);
|
||||
|
||||
// make sure the collection isn't sorted accidentally
|
||||
assertFalse("Oops: source collection is already sorted!", isSorted(srcCollection));
|
||||
}
|
||||
|
||||
/**
|
||||
* Section 3. Using the ArrayList Constructor
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingConstructor_thenVerifyShallowCopy() {
|
||||
ArrayList<Foo> newList = new ArrayList<>(srcCollection);
|
||||
verifyShallowCopy(srcCollection, newList);
|
||||
}
|
||||
|
||||
/**
|
||||
* Section 4. Using the Streams API
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingStream_thenVerifyShallowCopy() {
|
||||
ArrayList<Foo> newList = srcCollection.stream().collect(toCollection(ArrayList::new));
|
||||
|
||||
verifyShallowCopy(srcCollection, newList);
|
||||
}
|
||||
|
||||
/**
|
||||
* Section 5. Deep Copy
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingDeepCopy_thenVerifyDeepCopy() {
|
||||
ArrayList<Foo> newList = srcCollection.stream()
|
||||
.map(foo -> foo.deepCopy())
|
||||
.collect(toCollection(ArrayList::new));
|
||||
|
||||
verifyDeepCopy(srcCollection, newList);
|
||||
}
|
||||
|
||||
/**
|
||||
* Section 6. Controlling the List Order
|
||||
*/
|
||||
@Test
|
||||
public void whenUsingSortedStream_thenVerifySortOrder() {
|
||||
ArrayList<Foo> newList = srcCollection.stream()
|
||||
.sorted(Comparator.comparing(Foo::getName))
|
||||
.collect(toCollection(ArrayList::new));
|
||||
|
||||
assertTrue("ArrayList is not sorted by name", isSorted(newList));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that the contents of the two collections are the same
|
||||
* @param a
|
||||
* @param b
|
||||
*/
|
||||
private void verifyShallowCopy(Collection a, Collection b) {
|
||||
assertEquals("Collections have different lengths", a.size(), b.size());
|
||||
Iterator<Foo> iterA = a.iterator();
|
||||
Iterator<Foo> iterB = b.iterator();
|
||||
while (iterA.hasNext()) {
|
||||
// use '==' to test instance identity
|
||||
assertTrue("Foo instances differ!", iterA.next() == iterB.next());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that the contents of the two collections are the same
|
||||
* @param a
|
||||
* @param b
|
||||
*/
|
||||
private void verifyDeepCopy(Collection a, Collection b) {
|
||||
assertEquals("Collections have different lengths", a.size(), b.size());
|
||||
Iterator<Foo> iterA = a.iterator();
|
||||
Iterator<Foo> iterB = b.iterator();
|
||||
while (iterA.hasNext()) {
|
||||
Foo nextA = iterA.next();
|
||||
Foo nextB = iterB.next();
|
||||
// should not be same instance
|
||||
assertFalse("Foo instances are the same!", nextA == nextB);
|
||||
// but should have same content
|
||||
assertFalse("Foo instances have different content!", fooDiff(nextA, nextB));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the contents of a and b differ. Test parent recursively
|
||||
* @param a
|
||||
* @param b
|
||||
* @return False if the two items are the same
|
||||
*/
|
||||
private boolean fooDiff(Foo a, Foo b) {
|
||||
if (a != null && b != null) {
|
||||
return a.getId() != b.getId()
|
||||
|| !a.getName().equals(b.getName())
|
||||
|| fooDiff(a.getParent(), b.getParent());
|
||||
}
|
||||
return !(a == null && b == null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param c collection of Foo
|
||||
* @return true if the collection is sorted by name
|
||||
*/
|
||||
private static boolean isSorted(Collection<Foo> c) {
|
||||
String prevName = null;
|
||||
for (Foo foo : c) {
|
||||
if (prevName == null || foo.getName().compareTo(prevName) > 0) {
|
||||
prevName = foo.getName();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package com.baeldung.convertlisttomap;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
|
||||
public class ConvertListToMapServiceUnitTest {
|
||||
List<Animal> list;
|
||||
|
||||
private ConvertListToMapService convertListService;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
this.convertListService = new ConvertListToMapService();
|
||||
this.list = new ArrayList<>();
|
||||
|
||||
Animal cat = new Animal(1, "Cat");
|
||||
list.add(cat);
|
||||
Animal dog = new Animal(2, "Dog");
|
||||
list.add(dog);
|
||||
Animal pig = new Animal(3, "Pig");
|
||||
list.add(pig);
|
||||
Animal cow = new Animal(4, "Cow");
|
||||
list.add(cow);
|
||||
Animal goat = new Animal(5, "Goat");
|
||||
list.add(goat);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenConvertBeforeJava8_thenReturnMapWithTheSameElements() {
|
||||
|
||||
Map<Integer, Animal> map = convertListService.convertListBeforeJava8(list);
|
||||
|
||||
assertThat(map.values(), containsInAnyOrder(list.toArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenConvertAfterJava8_thenReturnMapWithTheSameElements() {
|
||||
|
||||
Map<Integer, Animal> map = convertListService.convertListAfterJava8(list);
|
||||
|
||||
assertThat(map.values(), containsInAnyOrder(list.toArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenConvertWithGuava_thenReturnMapWithTheSameElements() {
|
||||
|
||||
Map<Integer, Animal> map = convertListService.convertListWithGuava(list);
|
||||
|
||||
assertThat(map.values(), containsInAnyOrder(list.toArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenConvertWithApacheCommons_thenReturnMapWithTheSameElements() {
|
||||
|
||||
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons(list);
|
||||
|
||||
assertThat(map.values(), containsInAnyOrder(list.toArray()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package com.baeldung.convertlisttomap;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
|
||||
public class ConvertListWithDiplicatedIdToMapServiceUnitTest {
|
||||
List<Animal> duplicatedIdList;
|
||||
|
||||
private ConvertListToMapService convertListService = new ConvertListToMapService();
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
|
||||
this.duplicatedIdList = new ArrayList<>();
|
||||
|
||||
Animal cat = new Animal(1, "Cat");
|
||||
duplicatedIdList.add(cat);
|
||||
Animal dog = new Animal(2, "Dog");
|
||||
duplicatedIdList.add(dog);
|
||||
Animal pig = new Animal(3, "Pig");
|
||||
duplicatedIdList.add(pig);
|
||||
Animal cow = new Animal(4, "Cow");
|
||||
duplicatedIdList.add(cow);
|
||||
Animal goat = new Animal(4, "Goat");
|
||||
duplicatedIdList.add(goat);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenADupIdList_whenConvertBeforeJava8_thenReturnMapWithRewrittenElement() {
|
||||
|
||||
Map<Integer, Animal> map = convertListService.convertListBeforeJava8(duplicatedIdList);
|
||||
|
||||
assertThat(map.values(), hasSize(4));
|
||||
assertThat(map.values(), hasItem(duplicatedIdList.get(4)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenADupIdList_whenConvertWithApacheCommons_thenReturnMapWithRewrittenElement() {
|
||||
|
||||
Map<Integer, Animal> map = convertListService.convertListWithApacheCommons(duplicatedIdList);
|
||||
|
||||
assertThat(map.values(), hasSize(4));
|
||||
assertThat(map.values(), hasItem(duplicatedIdList.get(4)));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void givenADupIdList_whenConvertAfterJava8_thenException() {
|
||||
|
||||
convertListService.convertListAfterJava8(duplicatedIdList);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void givenADupIdList_whenConvertWithGuava_thenException() {
|
||||
|
||||
convertListService.convertListWithGuava(duplicatedIdList);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.java.map;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class KeyCheckUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenKeyIsPresent_thenContainsKeyReturnsTrue() {
|
||||
Map<String, String> map = Collections.singletonMap("key", "value");
|
||||
|
||||
assertTrue(map.containsKey("key"));
|
||||
assertFalse(map.containsKey("missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenKeyHasNullValue_thenGetStillWorks() {
|
||||
Map<String, String> map = Collections.singletonMap("nothing", null);
|
||||
|
||||
assertTrue(map.containsKey("nothing"));
|
||||
assertNull(map.get("nothing"));
|
||||
}
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
package com.baeldung.java.map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.collections4.MultiMap;
|
||||
import org.apache.commons.collections4.MultiMapUtils;
|
||||
import org.apache.commons.collections4.MultiValuedMap;
|
||||
import org.apache.commons.collections4.map.MultiValueMap;
|
||||
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
|
||||
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.collect.ArrayListMultimap;
|
||||
import com.google.common.collect.LinkedHashMultimap;
|
||||
import com.google.common.collect.Multimap;
|
||||
import com.google.common.collect.TreeMultimap;
|
||||
|
||||
public class MapMultipleValuesUnitTest {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MapMultipleValuesUnitTest.class);
|
||||
|
||||
@Test
|
||||
public void givenHashMap_whenPuttingTwice_thenReturningFirstValue() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
assertThat(map.put("key1", "value1")).isEqualTo(null);
|
||||
assertThat(map.put("key1", "value2")).isEqualTo("value1");
|
||||
assertThat(map.get("key1")).isEqualTo("value2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionAsValue_whenPuttingTwice_thenReturningCollection() {
|
||||
Map<String, List<String>> map = new HashMap<>();
|
||||
List<String> list = new ArrayList<>();
|
||||
map.put("key1", list);
|
||||
map.get("key1").add("value1");
|
||||
map.get("key1").add("value2");
|
||||
assertThat(map.get("key1").get(0)).isEqualTo("value1");
|
||||
assertThat(map.get("key1").get(1)).isEqualTo("value2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionAsValueAndJava8_whenPuttingTwice_thenReturningCollection() {
|
||||
Map<String, List<String>> map = new HashMap<>();
|
||||
map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value1");
|
||||
map.computeIfAbsent("key1", k -> new ArrayList<>()).add("value2");
|
||||
assertThat(map.get("key1").get(0)).isEqualTo("value1");
|
||||
assertThat(map.get("key1").get(1)).isEqualTo("value2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMultiValueMap_whenPuttingTwice_thenReturningValues() {
|
||||
MultiMap<String, String> map = new MultiValueMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key1", "value2");
|
||||
assertThat((Collection<String>) map.get("key1"))
|
||||
.contains("value1", "value2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayListValuedHashMap_whenPuttingDoubleValues_thenReturningAllValues() {
|
||||
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key1", "value2");
|
||||
map.put("key1", "value2");
|
||||
assertThat((Collection<String>) map.get("key1"))
|
||||
.containsExactly("value1", "value2", "value2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHashSetValuedHashMap_whenPuttingTwiceTheSame_thenReturningOneValue() {
|
||||
MultiValuedMap<String, String> map = new HashSetValuedHashMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key1", "value1");
|
||||
assertThat((Collection<String>) map.get("key1"))
|
||||
.containsExactly("value1");
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void givenUnmodifiableMultiValuedMap_whenInserting_thenThrowingException() {
|
||||
MultiValuedMap<String, String> map = new ArrayListValuedHashMap<>();
|
||||
map.put("key1", "value1");
|
||||
map.put("key1", "value2");
|
||||
MultiValuedMap<String, String> immutableMap =
|
||||
MultiMapUtils.unmodifiableMultiValuedMap(map);
|
||||
immutableMap.put("key1", "value3");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenArrayListMultiMap_whenInserting_thenCorrectOutput() {
|
||||
Multimap<String, String> map = ArrayListMultimap.create();
|
||||
map.put("key1", "value2");
|
||||
map.put("key1", "value1");
|
||||
assertThat((Collection<String>) map.get("key1"))
|
||||
.containsExactly("value2", "value1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedHashMultiMap_whenInserting_thenReturningValuesInInsertionOrder() {
|
||||
Multimap<String, String> map = LinkedHashMultimap.create();
|
||||
map.put("key1", "value3");
|
||||
map.put("key1", "value1");
|
||||
map.put("key1", "value2");
|
||||
assertThat((Collection<String>) map.get("key1"))
|
||||
.containsExactly("value3", "value1", "value2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeMultimap_whenInserting_thenReturningValuesInNaturalOrder() {
|
||||
Multimap<String, String> map = TreeMultimap.create();
|
||||
map.put("key1", "value3");
|
||||
map.put("key1", "value1");
|
||||
map.put("key1", "value2");
|
||||
assertThat((Collection<String>) map.get("key1"))
|
||||
.containsExactly("value1", "value2", "value3");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,336 +0,0 @@
|
||||
package com.baeldung.java.map;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class MapUnitTest {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MapUnitTest.class);
|
||||
|
||||
|
||||
@Test
|
||||
public void givenHashMap_whenRetrievesKeyset_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("name", "baeldung");
|
||||
map.put("type", "blog");
|
||||
|
||||
Set<String> keys = map.keySet();
|
||||
|
||||
assertEquals(2, keys.size());
|
||||
assertTrue(keys.contains("name"));
|
||||
assertTrue(keys.contains("type"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHashMap_whenRetrievesValues_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("name", "baeldung");
|
||||
map.put("type", "blog");
|
||||
|
||||
Collection<String> values = map.values();
|
||||
|
||||
assertEquals(2, values.size());
|
||||
assertTrue(values.contains("baeldung"));
|
||||
assertTrue(values.contains("blog"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHashMap_whenRetrievesEntries_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("name", "baeldung");
|
||||
map.put("type", "blog");
|
||||
|
||||
Set<Entry<String, String>> entries = map.entrySet();
|
||||
|
||||
assertEquals(2, entries.size());
|
||||
for (Entry<String, String> e : entries) {
|
||||
String key = e.getKey();
|
||||
String val = e.getValue();
|
||||
assertTrue(key.equals("name") || key.equals("type"));
|
||||
assertTrue(val.equals("baeldung") || val.equals("blog"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenKeySet_whenChangeReflectsInMap_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("name", "baeldung");
|
||||
map.put("type", "blog");
|
||||
|
||||
assertEquals(2, map.size());
|
||||
|
||||
Set<String> keys = map.keySet();
|
||||
|
||||
keys.remove("name");
|
||||
assertEquals(1, map.size());
|
||||
}
|
||||
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void givenIterator_whenFailsFastOnModification_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("name", "baeldung");
|
||||
map.put("type", "blog");
|
||||
|
||||
Set<String> keys = map.keySet();
|
||||
Iterator<String> it = keys.iterator();
|
||||
map.remove("type");
|
||||
while (it.hasNext()) {
|
||||
String key = it.next();
|
||||
}
|
||||
}
|
||||
|
||||
public void givenIterator_whenRemoveWorks_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("name", "baeldung");
|
||||
map.put("type", "blog");
|
||||
|
||||
Set<String> keys = map.keySet();
|
||||
Iterator<String> it = keys.iterator();
|
||||
while (it.hasNext()) {
|
||||
it.next();
|
||||
it.remove();
|
||||
}
|
||||
assertEquals(0, map.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHashCodeIsCalledOnPut_thenCorrect() {
|
||||
MyKey key = new MyKey(1, "name");
|
||||
Map<MyKey, String> map = new HashMap<>();
|
||||
map.put(key, "val");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenHashCodeIsCalledOnGet_thenCorrect() {
|
||||
MyKey key = new MyKey(1, "name");
|
||||
Map<MyKey, String> map = new HashMap<>();
|
||||
map.put(key, "val");
|
||||
map.get(key);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetWorks_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key", "val");
|
||||
|
||||
String val = map.get("key");
|
||||
|
||||
assertEquals("val", val);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewKey_whenPutReturnsNull_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
String rtnVal = map.put("key1", "val1");
|
||||
|
||||
assertNull(rtnVal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnmappedKey_whenGetReturnsNull_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
String rtnVal = map.get("key1");
|
||||
|
||||
assertNull(rtnVal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullVal_whenPutReturnsNull_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
String rtnVal = map.put("key1", null);
|
||||
|
||||
assertNull(rtnVal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullKeyAndVal_whenAccepts_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
map.put(null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNullVal_whenRetrieves_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key", null);
|
||||
|
||||
String val = map.get("key");
|
||||
|
||||
assertNull(val);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenContainsDistinguishesNullValues_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
String val1 = map.get("key");
|
||||
boolean valPresent = map.containsKey("key");
|
||||
|
||||
assertNull(val1);
|
||||
assertFalse(valPresent);
|
||||
|
||||
map.put("key", null);
|
||||
String val = map.get("key");
|
||||
valPresent = map.containsKey("key");
|
||||
|
||||
assertNull(val);
|
||||
assertTrue(valPresent);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPutReturnsPrevValue_thenCorrect() {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key1", "val1");
|
||||
String rtnVal = map.put("key1", "val2");
|
||||
|
||||
assertEquals("val1", rtnVal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCallsEqualsOnCollision_thenCorrect() {
|
||||
HashMap<MyKey, String> map = new HashMap<>();
|
||||
MyKey k1 = new MyKey(1, "firstKey");
|
||||
MyKey k2 = new MyKey(2, "secondKey");
|
||||
MyKey k3 = new MyKey(2, "thirdKey");
|
||||
|
||||
LOG.debug("storing value for k1");
|
||||
map.put(k1, "firstValue");
|
||||
|
||||
LOG.debug("storing value for k2");
|
||||
map.put(k2, "secondValue");
|
||||
|
||||
LOG.debug("storing value for k3");
|
||||
map.put(k3, "thirdValue");
|
||||
|
||||
LOG.debug("retrieving value for k1");
|
||||
String v1 = map.get(k1);
|
||||
|
||||
LOG.debug("retrieving value for k2");
|
||||
String v2 = map.get(k2);
|
||||
|
||||
LOG.debug("retrieving value for k3");
|
||||
String v3 = map.get(k3);
|
||||
|
||||
assertEquals("firstValue", v1);
|
||||
assertEquals("secondValue", v2);
|
||||
assertEquals("thirdValue", v3);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedHashMap_whenGetsOrderedKeyset_thenCorrect() {
|
||||
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
|
||||
map.put(1, null);
|
||||
map.put(2, null);
|
||||
map.put(3, null);
|
||||
map.put(4, null);
|
||||
map.put(5, null);
|
||||
Set<Integer> keys = map.keySet();
|
||||
Integer[] arr = keys.toArray(new Integer[0]);
|
||||
for (int i = 0; i < arr.length; i++) {
|
||||
assertEquals(new Integer(i + 1), arr[i]);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedHashMap_whenAccessOrderWorks_thenCorrect() {
|
||||
LinkedHashMap<Integer, String> map = new LinkedHashMap<>(16, .75f, true);
|
||||
map.put(1, null);
|
||||
map.put(2, null);
|
||||
map.put(3, null);
|
||||
map.put(4, null);
|
||||
map.put(5, null);
|
||||
Set<Integer> keys = map.keySet();
|
||||
assertEquals("[1, 2, 3, 4, 5]", keys.toString());
|
||||
map.get(4);
|
||||
assertEquals("[1, 2, 3, 5, 4]", keys.toString());
|
||||
map.get(1);
|
||||
assertEquals("[2, 3, 5, 4, 1]", keys.toString());
|
||||
map.get(3);
|
||||
assertEquals("[2, 5, 4, 1, 3]", keys.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLinkedHashMap_whenRemovesEldestEntry_thenCorrect() {
|
||||
LinkedHashMap<Integer, String> map = new MyLinkedHashMap<>(16, .75f, true);
|
||||
map.put(1, null);
|
||||
map.put(2, null);
|
||||
map.put(3, null);
|
||||
map.put(4, null);
|
||||
map.put(5, null);
|
||||
Set<Integer> keys = map.keySet();
|
||||
assertEquals("[1, 2, 3, 4, 5]", keys.toString());
|
||||
map.put(6, null);
|
||||
assertEquals("[2, 3, 4, 5, 6]", keys.toString());
|
||||
map.put(7, null);
|
||||
assertEquals("[3, 4, 5, 6, 7]", keys.toString());
|
||||
map.put(8, null);
|
||||
assertEquals("[4, 5, 6, 7, 8]", keys.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect() {
|
||||
TreeMap<Integer, String> map = new TreeMap<>();
|
||||
map.put(3, "val");
|
||||
map.put(2, "val");
|
||||
map.put(1, "val");
|
||||
map.put(5, "val");
|
||||
map.put(4, "val");
|
||||
assertEquals("[1, 2, 3, 4, 5]", map.keySet().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeMap_whenOrdersEntriesNaturally_thenCorrect2() {
|
||||
TreeMap<String, String> map = new TreeMap<>();
|
||||
map.put("c", "val");
|
||||
map.put("b", "val");
|
||||
map.put("a", "val");
|
||||
map.put("e", "val");
|
||||
map.put("d", "val");
|
||||
|
||||
assertEquals("[a, b, c, d, e]", map.keySet().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() {
|
||||
TreeMap<Integer, String> map = new TreeMap<>(Comparator.reverseOrder());
|
||||
map.put(3, "val");
|
||||
map.put(2, "val");
|
||||
map.put(1, "val");
|
||||
map.put(5, "val");
|
||||
map.put(4, "val");
|
||||
|
||||
assertEquals("[5, 4, 3, 2, 1]", map.keySet().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTreeMap_whenPerformsQueries_thenCorrect() {
|
||||
TreeMap<Integer, String> map = new TreeMap<>();
|
||||
map.put(3, "val");
|
||||
map.put(2, "val");
|
||||
map.put(1, "val");
|
||||
map.put(5, "val");
|
||||
map.put(4, "val");
|
||||
|
||||
Integer highestKey = map.lastKey();
|
||||
Integer lowestKey = map.firstKey();
|
||||
Set<Integer> keysLessThan3 = map.headMap(3).keySet();
|
||||
Set<Integer> keysGreaterThanEqTo3 = map.tailMap(3).keySet();
|
||||
|
||||
assertEquals(new Integer(5), highestKey);
|
||||
assertEquals(new Integer(1), lowestKey);
|
||||
assertEquals("[1, 2]", keysLessThan3.toString());
|
||||
assertEquals("[3, 4, 5]", keysGreaterThanEqTo3.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.java.map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.collections4.BidiMap;
|
||||
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.HashBiMap;
|
||||
|
||||
/**
|
||||
* @author swpraman
|
||||
*
|
||||
*/
|
||||
public class MapUtilUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void whenUsingImperativeWayForSingleKey_shouldReturnSingleKey() {
|
||||
Map<String, String> capitalCountryMap = new HashMap<>();
|
||||
capitalCountryMap.put("Tokyo", "Japan");
|
||||
capitalCountryMap.put("New Delhi", "India");
|
||||
assertEquals("New Delhi", MapUtil.getKey(capitalCountryMap, "India"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingImperativeWayForAllKeys_shouldReturnAllKeys() {
|
||||
Map<String, String> capitalCountryMap = new HashMap<>();
|
||||
capitalCountryMap.put("Tokyo", "Japan");
|
||||
capitalCountryMap.put("Berlin", "Germany");
|
||||
capitalCountryMap.put("Cape Town", "South Africa");
|
||||
capitalCountryMap.put("Pretoria", "South Africa");
|
||||
capitalCountryMap.put("Bloemfontein", "South Africa");
|
||||
|
||||
assertEquals(new HashSet<String>(Arrays.asList(
|
||||
new String[] {"Cape Town", "Pretoria", "Bloemfontein"})),
|
||||
MapUtil.getKeys(capitalCountryMap, "South Africa"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFunctionalWayForSingleKey_shouldReturnSingleKey() {
|
||||
Map<String, String> capitalCountryMap = new HashMap<>();
|
||||
capitalCountryMap.put("Tokyo", "Japan");
|
||||
capitalCountryMap.put("Berlin", "Germany");
|
||||
assertEquals("Berlin", MapUtil.keys(capitalCountryMap, "Germany").findFirst().get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFunctionalWayForAllKeys_shouldReturnAllKeys() {
|
||||
Map<String, String> capitalCountryMap = new HashMap<>();
|
||||
capitalCountryMap.put("Tokyo", "Japan");
|
||||
capitalCountryMap.put("Berlin", "Germany");
|
||||
capitalCountryMap.put("Cape Town", "South Africa");
|
||||
capitalCountryMap.put("Pretoria", "South Africa");
|
||||
capitalCountryMap.put("Bloemfontein", "South Africa");
|
||||
assertEquals(new HashSet<String>(Arrays.asList(
|
||||
new String[] {"Cape Town", "Pretoria", "Bloemfontein"})),
|
||||
MapUtil.keys(capitalCountryMap, "South Africa").collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBidiMap_shouldReturnKey() {
|
||||
BidiMap<String, String> capitalCountryMap = new DualHashBidiMap<String, String>();
|
||||
capitalCountryMap.put("Berlin", "Germany");
|
||||
capitalCountryMap.put("Cape Town", "South Africa");
|
||||
assertEquals("Berlin", capitalCountryMap.getKey("Germany"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBidiMapAddDuplicateValue_shouldRemoveOldEntry() {
|
||||
BidiMap<String, String> capitalCountryMap = new DualHashBidiMap<String, String>();
|
||||
capitalCountryMap.put("Berlin", "Germany");
|
||||
capitalCountryMap.put("Cape Town", "South Africa");
|
||||
capitalCountryMap.put("Pretoria", "South Africa");
|
||||
assertEquals("Pretoria", capitalCountryMap.getKey("South Africa"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBiMap_shouldReturnKey() {
|
||||
HashBiMap<String, String> capitalCountryMap = HashBiMap.create();
|
||||
capitalCountryMap.put("Berlin", "Germany");
|
||||
capitalCountryMap.put("Cape Town", "South Africa");
|
||||
assertEquals("Berlin", capitalCountryMap.inverse().get("Germany"));
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingBiMapAddDuplicateValue_shouldThrowException() {
|
||||
HashBiMap<String, String> capitalCountryMap = HashBiMap.create();
|
||||
capitalCountryMap.put("Berlin", "Germany");
|
||||
capitalCountryMap.put("Cape Town", "South Africa");
|
||||
capitalCountryMap.put("Pretoria", "South Africa");
|
||||
assertEquals("Berlin", capitalCountryMap.inverse().get("Germany"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.java.map.initialize;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class MapInitializerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenStaticMap_whenUpdated_thenCorrect() {
|
||||
|
||||
MapInitializer.articleMapOne.put("NewArticle1", "Convert array to List");
|
||||
|
||||
assertEquals(MapInitializer.articleMapOne.get("NewArticle1"), "Convert array to List");
|
||||
|
||||
}
|
||||
|
||||
@Test(expected=UnsupportedOperationException.class)
|
||||
public void givenSingleTonMap_whenEntriesAdded_throwsException() {
|
||||
|
||||
Map<String, String> map = MapInitializer.createSingletonMap();
|
||||
map.put("username2", "password2");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package com.baeldung.map.util;
|
||||
|
||||
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class MapMaxUnitTest {
|
||||
|
||||
Map<Integer, Integer> map = null;
|
||||
MapMax mapMax = null;
|
||||
|
||||
|
||||
@Before
|
||||
public void setupTestData() {
|
||||
map = new HashMap<Integer, Integer>();
|
||||
map.put(23, 12);
|
||||
map.put(46, 24);
|
||||
map.put(27, 38);
|
||||
mapMax = new MapMax();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMap_whenIterated_thenReturnMaxValue() {
|
||||
assertEquals(new Integer(38), mapMax.maxUsingIteration(map));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMap_whenUsingCollectionsMax_thenReturnMaxValue() {
|
||||
assertEquals(new Integer(38), mapMax.maxUsingCollectionsMax(map));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMap_whenUsingCollectionsMaxAndLambda_thenReturnMaxValue() {
|
||||
assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndLambda(map));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMap_whenUsingCollectionsMaxAndMethodReference_thenReturnMaxValue() {
|
||||
assertEquals(new Integer(38), mapMax.maxUsingCollectionsMaxAndMethodReference(map));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMap_whenUsingStreamAndLambda_thenReturnMaxValue() {
|
||||
assertEquals(new Integer(38), mapMax.maxUsingStreamAndLambda(map));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenMap_whenUsingStreamAndMethodReference_thenReturnMaxValue() {
|
||||
assertEquals(new Integer(38), mapMax.maxUsingStreamAndMethodReference (map));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package com.baeldung.weakhashmap;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.WeakHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.jayway.awaitility.Awaitility.await;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class WeakHashMapUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObject() {
|
||||
//given
|
||||
WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>();
|
||||
BigImage bigImage = new BigImage("image_id");
|
||||
UniqueImageName imageName = new UniqueImageName("name_of_big_image");
|
||||
|
||||
map.put(imageName, bigImage);
|
||||
assertTrue(map.containsKey(imageName));
|
||||
|
||||
//when big image key is not reference anywhere
|
||||
imageName = null;
|
||||
System.gc();
|
||||
|
||||
//then GC will finally reclaim that object
|
||||
await().atMost(10, TimeUnit.SECONDS).until(map::isEmpty);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWeakHashMap_whenCacheValueThatHasNoReferenceToIt_GCShouldReclaimThatObjectButLeaveReferencedObject() {
|
||||
//given
|
||||
WeakHashMap<UniqueImageName, BigImage> map = new WeakHashMap<>();
|
||||
BigImage bigImageFirst = new BigImage("foo");
|
||||
UniqueImageName imageNameFirst = new UniqueImageName("name_of_big_image");
|
||||
|
||||
BigImage bigImageSecond = new BigImage("foo_2");
|
||||
UniqueImageName imageNameSecond = new UniqueImageName("name_of_big_image_2");
|
||||
|
||||
map.put(imageNameFirst, bigImageFirst);
|
||||
map.put(imageNameSecond, bigImageSecond);
|
||||
assertTrue(map.containsKey(imageNameFirst));
|
||||
assertTrue(map.containsKey(imageNameSecond));
|
||||
|
||||
//when
|
||||
imageNameFirst = null;
|
||||
System.gc();
|
||||
|
||||
//then
|
||||
await().atMost(10, TimeUnit.SECONDS).until(() -> map.size() == 1);
|
||||
await().atMost(10, TimeUnit.SECONDS).until(() -> map.containsKey(imageNameSecond));
|
||||
}
|
||||
|
||||
|
||||
class BigImage {
|
||||
public final String imageId;
|
||||
|
||||
BigImage(String imageId) {
|
||||
this.imageId = imageId;
|
||||
}
|
||||
}
|
||||
|
||||
class UniqueImageName {
|
||||
public final String imageName;
|
||||
|
||||
UniqueImageName(String imageName) {
|
||||
this.imageName = imageName;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,187 +0,0 @@
|
||||
package org.baeldung.java.collections;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
import com.google.common.primitives.Ints;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public class JavaCollectionConversionUnitTest {
|
||||
|
||||
// List -> array; array -> List
|
||||
|
||||
@Test
|
||||
public final void givenUsingCoreJava_whenArrayConvertedToList_thenCorrect() {
|
||||
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
|
||||
final List<Integer> targetList = Arrays.asList(sourceArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCoreJava_whenListConvertedToArray_thenCorrect() {
|
||||
final List<Integer> sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
|
||||
final Integer[] targetArray = sourceList.toArray(new Integer[sourceList.size()]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenArrayConvertedToList_thenCorrect() {
|
||||
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
|
||||
final List<Integer> targetList = Lists.newArrayList(sourceArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenListConvertedToArray_thenCorrect() {
|
||||
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
|
||||
final int[] targetArray = Ints.toArray(sourceList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsCollections_whenArrayConvertedToList_thenCorrect() {
|
||||
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
|
||||
final List<Integer> targetList = new ArrayList<>(6);
|
||||
CollectionUtils.addAll(targetList, sourceArray);
|
||||
}
|
||||
|
||||
// Set -> array; array -> Set
|
||||
|
||||
@Test
|
||||
public final void givenUsingCoreJavaV1_whenArrayConvertedToSet_thenCorrect() {
|
||||
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
|
||||
final Set<Integer> targetSet = new HashSet<Integer>(Arrays.asList(sourceArray));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCoreJavaV2_whenArrayConvertedToSet_thenCorrect() {
|
||||
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
|
||||
final Set<Integer> targetSet = new HashSet<Integer>();
|
||||
Collections.addAll(targetSet, sourceArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCoreJava_whenSetConvertedToArray_thenCorrect() {
|
||||
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
|
||||
final Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenArrayConvertedToSet_thenCorrect() {
|
||||
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
|
||||
final Set<Integer> targetSet = Sets.newHashSet(sourceArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenSetConvertedToArray_thenCorrect() {
|
||||
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
|
||||
final int[] targetArray = Ints.toArray(sourceSet);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsCollections_whenArrayConvertedToSet_thenCorrect() {
|
||||
final Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
|
||||
final Set<Integer> targetSet = new HashSet<>(6);
|
||||
CollectionUtils.addAll(targetSet, sourceArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsCollections_whenSetConvertedToArray_thenCorrect() {
|
||||
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
|
||||
final Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsCollections_whenSetConvertedToArrayOfPrimitives_thenCorrect() {
|
||||
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
|
||||
final Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]);
|
||||
final int[] primitiveTargetArray = ArrayUtils.toPrimitive(targetArray);
|
||||
}
|
||||
|
||||
// Set -> List; List -> Set
|
||||
|
||||
public final void givenUsingCoreJava_whenSetConvertedToList_thenCorrect() {
|
||||
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
|
||||
final List<Integer> targetList = new ArrayList<>(sourceSet);
|
||||
}
|
||||
|
||||
public final void givenUsingCoreJava_whenListConvertedToSet_thenCorrect() {
|
||||
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
|
||||
final Set<Integer> targetSet = new HashSet<>(sourceList);
|
||||
}
|
||||
|
||||
public final void givenUsingGuava_whenSetConvertedToList_thenCorrect() {
|
||||
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
|
||||
final List<Integer> targetList = Lists.newArrayList(sourceSet);
|
||||
}
|
||||
|
||||
public final void givenUsingGuava_whenListConvertedToSet_thenCorrect() {
|
||||
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
|
||||
final Set<Integer> targetSet = Sets.newHashSet(sourceList);
|
||||
}
|
||||
|
||||
public final void givenUsingCommonsCollections_whenListConvertedToSet_thenCorrect() {
|
||||
final List<Integer> sourceList = Lists.newArrayList(0, 1, 2, 3, 4, 5);
|
||||
|
||||
final Set<Integer> targetSet = new HashSet<>(6);
|
||||
CollectionUtils.addAll(targetSet, sourceList);
|
||||
}
|
||||
|
||||
public final void givenUsingCommonsCollections_whenSetConvertedToList_thenCorrect() {
|
||||
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
|
||||
|
||||
final List<Integer> targetList = new ArrayList<>(6);
|
||||
CollectionUtils.addAll(targetList, sourceSet);
|
||||
}
|
||||
|
||||
// Map (values) -> Array, List, Set
|
||||
|
||||
@Test
|
||||
public final void givenUsingCoreJava_whenMapValuesConvertedToArray_thenCorrect() {
|
||||
final Map<Integer, String> sourceMap = createMap();
|
||||
|
||||
final Collection<String> values = sourceMap.values();
|
||||
final String[] targetArray = values.toArray(new String[values.size()]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCoreJava_whenMapValuesConvertedToList_thenCorrect() {
|
||||
final Map<Integer, String> sourceMap = createMap();
|
||||
|
||||
final List<String> targetList = new ArrayList<>(sourceMap.values());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenMapValuesConvertedToList_thenCorrect() {
|
||||
final Map<Integer, String> sourceMap = createMap();
|
||||
|
||||
final List<String> targetList = Lists.newArrayList(sourceMap.values());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingCoreJava_whenMapValuesConvertedToSet_thenCorrect() {
|
||||
final Map<Integer, String> sourceMap = createMap();
|
||||
|
||||
final Set<String> targetSet = new HashSet<>(sourceMap.values());
|
||||
}
|
||||
|
||||
// UTIL
|
||||
|
||||
private final Map<Integer, String> createMap() {
|
||||
final Map<Integer, String> sourceMap = new HashMap<>(3);
|
||||
sourceMap.put(0, "zero");
|
||||
sourceMap.put(1, "one");
|
||||
sourceMap.put(2, "two");
|
||||
return sourceMap;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package org.baeldung.java.lists;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ListToSTring {
|
||||
|
||||
@Test
|
||||
public void whenListToString_thenPrintDefault() {
|
||||
List<Integer> intLIst = Arrays.asList(1, 2, 3);
|
||||
System.out.println(intLIst);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectorsJoining_thenPrintCustom() {
|
||||
List<Integer> intList = Arrays.asList(1, 2, 3);
|
||||
System.out.println(intList.stream()
|
||||
.map(n -> String.valueOf(n))
|
||||
.collect(Collectors.joining("-", "{", "}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStringUtilsJoin_thenPrintCustom() {
|
||||
List<Integer> intList = Arrays.asList(1, 2, 3);
|
||||
System.out.println(StringUtils.join(intList, "|"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user