This commit is contained in:
YuCheng Hu 2023-04-21 17:09:52 -04:00
parent 662b8184c0
commit e5d5c2dcbe
19 changed files with 2 additions and 982 deletions

10
.idea/.gitignore vendored
View File

@ -1,10 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Zeppelin ignored files
/ZeppelinRemoteNotebooks/

View File

@ -2,7 +2,6 @@
<project version="4"> <project version="4">
<component name="CompilerConfiguration"> <component name="CompilerConfiguration">
<annotationProcessing> <annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true"> <profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" /> <sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" /> <sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
@ -22,10 +21,10 @@
<module name="core-java" /> <module name="core-java" />
<module name="core-java-11" /> <module name="core-java-11" />
<module name="core-java-collections-conversions" /> <module name="core-java-collections-conversions" />
<module name="core-java-collections-list-2" />
<module name="core-java-collections" /> <module name="core-java-collections" />
<module name="core-java-datetime-conversion" /> <module name="core-java-collections-list-2" />
<module name="core-java-collections-list-3" /> <module name="core-java-collections-list-3" />
<module name="core-java-datetime-conversion" />
<module name="core-java-8" /> <module name="core-java-8" />
<module name="junit-5-basics" /> <module name="junit-5-basics" />
<module name="core-java-collections-3" /> <module name="core-java-collections-3" />
@ -33,11 +32,6 @@
<module name="activejdbc" /> <module name="activejdbc" />
</profile> </profile>
</annotationProcessing> </annotationProcessing>
<bytecodeTargetLevel>
<module name="core-java-11-2" target="11" />
<module name="hibernate-annotations" target="1.5" />
<module name="hibernate5" target="11" />
</bytecodeTargetLevel>
</component> </component>
<component name="JavacSettings"> <component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE"> <option name="ADDITIONAL_OPTIONS_OVERRIDE">

View File

@ -1,8 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="Encoding"> <component name="Encoding">
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-11-2/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-11-2/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-11/src/main/java" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/core-java-modules/core-java-11/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-11/src/main/resources" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/core-java-modules/core-java-11/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-8-2/src/main/java" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/core-java-modules/core-java-8-2/src/main/java" charset="UTF-8" />
@ -41,8 +39,6 @@
<file url="file://$PROJECT_DIR$/core-java-modules/src/main/resources" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/core-java-modules/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/activejdbc/src/main/java" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/persistence-modules/activejdbc/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/activejdbc/src/main/resources" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/persistence-modules/activejdbc/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/hibernate5/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/hibernate5/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-jpa-repo-2/src/main/java" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/persistence-modules/spring-data-jpa-repo-2/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-jpa-repo-2/src/main/resources" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/persistence-modules/spring-data-jpa-repo-2/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/persistence-modules/spring-data-redis/src/main/java" charset="UTF-8" /> <file url="file://$PROJECT_DIR$/persistence-modules/spring-data-redis/src/main/java" charset="UTF-8" />

View File

@ -6,16 +6,6 @@
<option name="name" value="OSSEZ Private Snapshots" /> <option name="name" value="OSSEZ Private Snapshots" />
<option name="url" value="https://repo.ossez.com/repository/maven-snapshots/" /> <option name="url" value="https://repo.ossez.com/repository/maven-snapshots/" />
</remote-repository> </remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="geodb-repo" />
<option name="name" value="GeoDB repository" />
<option name="url" value="http://repo.boundlessgeo.com/main/" />
</remote-repository>
<remote-repository> <remote-repository>
<option name="id" value="ossez-repo-releases" /> <option name="id" value="ossez-repo-releases" />
<option name="name" value="OSSEZ Private Releases" /> <option name="name" value="OSSEZ Private Releases" />

View File

@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MessDetectorOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCSFixerOptionsConfiguration">
<option name="transferred" value="true" />
</component>
<component name="PHPCodeSnifferOptionsConfiguration">
<option name="transferred" value="true" />
</component>
</project>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ThriftCompiler">
<compilers />
</component>
</project>

View File

@ -1,48 +0,0 @@
package com.baeldung.convertToMap;
public class Book {
private String name;
private int releaseYear;
private String isbn;
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", releaseYear=" + releaseYear +
", isbn='" + isbn + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getReleaseYear() {
return releaseYear;
}
public void setReleaseYear(int releaseYear) {
this.releaseYear = releaseYear;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Book(String name, int releaseYear, String isbn) {
this.name = name;
this.releaseYear = releaseYear;
this.isbn = isbn;
}
}

View File

@ -1,30 +0,0 @@
package com.baeldung.convertToMap;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ConvertToMap {
public Map<String, String> listToMap(List<Book> books) {
return books.stream().collect(Collectors.toMap(Book::getIsbn, Book::getName));
}
public Map<Integer, Book> listToMapWithDupKeyError(List<Book> books) {
return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity()));
}
public Map<Integer, Book> listToMapWithDupKey(List<Book> books) {
return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(), (existing, replacement) -> existing));
}
public Map<Integer, Book> listToConcurrentMap(List<Book> books) {
return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(), (o1, o2) -> o1, ConcurrentHashMap::new));
}
public TreeMap<String, Book> listToSortedMap(List<Book> books) {
return books.stream()
.collect(Collectors.toMap(Book::getName, Function.identity(), (o1, o2) -> o1, TreeMap::new));
}
}

View File

@ -1,52 +0,0 @@
package com.baeldung.convertcollectiontoarraylist;
/**
* This POJO is the element type of our collection. It has a deepCopy() method.
*
* @author chris
*/
public class Foo {
private int id;
private String name;
private Foo parent;
public Foo() {
}
public Foo(int id, String name, Foo parent) {
this.id = id;
this.name = name;
this.parent = parent;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Foo getParent() {
return parent;
}
public void setParent(Foo parent) {
this.parent = parent;
}
public Foo deepCopy() {
return new Foo(
this.id, this.name, this.parent != null ? this.parent.deepCopy() : null);
}
}

View File

@ -1,27 +0,0 @@
package com.baeldung.convertlisttomap;
public class Animal {
private int id;
private String name;
public Animal(int id, String name) {
this.id = id;
this.setName(name);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,43 +0,0 @@
package com.baeldung.convertlisttomap;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.MapUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class ConvertListToMapService {
public Map<Integer, Animal> convertListBeforeJava8(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<>();
for (Animal animal : list) {
map.put(animal.getId(), animal);
}
return map;
}
public Map<Integer, Animal> convertListAfterJava8(List<Animal> list) {
Map<Integer, Animal> map = list.stream().collect(Collectors.toMap(Animal::getId, Function.identity()));
return map;
}
public Map<Integer, Animal> convertListWithGuava(List<Animal> list) {
Map<Integer, Animal> map = Maps.uniqueIndex(list, Animal::getId);
return map;
}
public Map<Integer, Animal> convertListWithApacheCommons(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<>();
MapUtils.populateMap(map, list, Animal::getId);
return map;
}
}

View File

@ -1,53 +0,0 @@
package com.baeldung.convertToMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class ConvertToMapUnitTest {
private List<Book> bookList;
private ConvertToMap convertToMap = new ConvertToMap();
@Before
public void init() {
bookList = new ArrayList<>();
bookList.add(new Book("The Fellowship of the Ring", 1954, "0395489318"));
bookList.add(new Book("The Two Towers", 1954, "0345339711"));
bookList.add(new Book("The Return of the King", 1955, "0618129111"));
}
@Test
public void whenConvertFromListToMap() {
assertTrue(convertToMap.listToMap(bookList).size() == 3);
}
@Test(expected = IllegalStateException.class)
public void whenMapHasDuplicateKey_without_merge_function_then_runtime_exception() {
convertToMap.listToMapWithDupKeyError(bookList);
}
@Test
public void whenMapHasDuplicateKeyThenMergeFunctionHandlesCollision() {
Map<Integer, Book> booksByYear = convertToMap.listToMapWithDupKey(bookList);
assertEquals(2, booksByYear.size());
assertEquals("0395489318", booksByYear.get(1954).getIsbn());
}
@Test
public void whenCreateConcurrentHashMap() {
assertTrue(convertToMap.listToConcurrentMap(bookList) instanceof ConcurrentHashMap);
}
@Test
public void whenMapisSorted() {
assertTrue(convertToMap.listToSortedMap(bookList).firstKey().equals("The Fellowship of the Ring"));
}
}

View File

@ -1,145 +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 CollectionToArrayListUnitTest {
private static Collection<Foo> srcCollection = new HashSet<>();
public CollectionToArrayListUnitTest() {
}
@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);
}
/**
* 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::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<Foo> a, Collection<Foo> b) {
assertEquals("Collections have different lengths", a.size(), b.size());
Iterator<Foo> iterA = a.iterator();
Iterator<Foo> iterB = b.iterator();
while (iterA.hasNext()) {
// test instance identity
assertSame("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<Foo> a, Collection<Foo> 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
assertNotSame("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;
}
}

View File

@ -1,100 +0,0 @@
package com.baeldung.convertiteratortolist;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.commons.collections4.IteratorUtils;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class ConvertIteratorToListServiceUnitTest {
Iterator<Integer> iterator;
@Before
public void setUp() {
iterator = Arrays.asList(1, 2, 3)
.iterator();
}
@Test
public void givenAnIterator_whenConvertIteratorToListUsingWhileLoop_thenReturnAList() {
List<Integer> actualList = new ArrayList<>();
// Convert Iterator to List using while loop dsf
while (iterator.hasNext()) {
actualList.add(iterator.next());
}
assertThat(actualList, hasSize(3));
assertThat(actualList, containsInAnyOrder(1, 2, 3));
}
@Test
public void givenAnIterator_whenConvertIteratorToListAfterJava8_thenReturnAList() {
List<Integer> actualList = new ArrayList<>();
// Convert Iterator to List using Java 8
iterator.forEachRemaining(actualList::add);
assertThat(actualList, hasSize(3));
assertThat(actualList, containsInAnyOrder(1, 2, 3));
}
@Test
public void givenAnIterator_whenConvertIteratorToListJava8Stream_thenReturnAList() {
// Convert iterator to iterable
Iterable<Integer> iterable = () -> iterator;
// Extract List from stream
List<Integer> actualList = StreamSupport
.stream(iterable.spliterator(), false)
.collect(Collectors.toList());
assertThat(actualList, hasSize(3));
assertThat(actualList, containsInAnyOrder(1, 2, 3));
}
@Test
public void givenAnIterator_whenConvertIteratorToImmutableListWithGuava_thenReturnAList() {
// Convert Iterator to an Immutable list using Guava library in Java
List<Integer> actualList = ImmutableList.copyOf(iterator);
assertThat(actualList, hasSize(3));
assertThat(actualList, containsInAnyOrder(1, 2, 3));
}
@Test
public void givenAnIterator_whenConvertIteratorToMutableListWithGuava_thenReturnAList() {
// Convert Iterator to a mutable list using Guava library in Java
List<Integer> actualList = Lists.newArrayList(iterator);
assertThat(actualList, hasSize(3));
assertThat(actualList, containsInAnyOrder(1, 2, 3));
}
@Test
public void givenAnIterator_whenConvertIteratorToMutableListWithApacheCommons_thenReturnAList() {
// Convert Iterator to a mutable list using Apache Commons library in Java
List<Integer> actualList = IteratorUtils.toList(iterator);
assertThat(actualList, hasSize(3));
assertThat(actualList, containsInAnyOrder(1, 2, 3));
}
}

View File

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

View File

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

View File

@ -1,122 +0,0 @@
package com.baeldung.java.collections;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.collections4.IteratorUtils;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class IterableToCollectionUnitTest {
Iterable<String> iterable = Arrays.asList("john", "tom", "jane");
Iterator<String> iterator = iterable.iterator();
@Test
public void whenConvertIterableToListUsingJava_thenSuccess() {
List<String> result = new ArrayList<String>();
for (String str : iterable) {
result.add(str);
}
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIterableToListUsingJava8_thenSuccess() {
List<String> result = new ArrayList<String>();
iterable.forEach(result::add);
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIterableToListUsingJava8WithSpliterator_thenSuccess() {
List<String> result = StreamSupport.stream(iterable.spliterator(), false)
.collect(Collectors.toList());
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIterableToListUsingGuava_thenSuccess() {
List<String> result = Lists.newArrayList(iterable);
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIterableToImmutableListUsingGuava_thenSuccess() {
List<String> result = ImmutableList.copyOf(iterable);
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIterableToListUsingApacheCommons_thenSuccess() {
List<String> result = IterableUtils.toList(iterable);
assertThat(result, contains("john", "tom", "jane"));
}
// ======================== Iterator
@Test
public void whenConvertIteratorToListUsingJava_thenSuccess() {
List<String> result = new ArrayList<String>();
while (iterator.hasNext()) {
result.add(iterator.next());
}
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIteratorToListUsingJava8_thenSuccess() {
List<String> result = new ArrayList<String>();
iterator.forEachRemaining(result::add);
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIteratorToListUsingJava8WithSpliterator_thenSuccess() {
List<String> result = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
.collect(Collectors.toList());
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIteratorToListUsingGuava_thenSuccess() {
List<String> result = Lists.newArrayList(iterator);
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIteratorToImmutableListUsingGuava_thenSuccess() {
List<String> result = ImmutableList.copyOf(iterator);
assertThat(result, contains("john", "tom", "jane"));
}
@Test
public void whenConvertIteratorToListUsingApacheCommons_thenSuccess() {
List<String> result = IteratorUtils.toList(iterator);
assertThat(result, contains("john", "tom", "jane"));
}
}

View File

@ -1,145 +0,0 @@
package com.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[0]);
}
@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[0]);
}
@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_whenSetConvertedToArrayOfPrimitives_thenCorrect() {
final Set<Integer> sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5);
final Integer[] targetArray = sourceSet.toArray(new Integer[0]);
final int[] primitiveTargetArray = ArrayUtils.toPrimitive(targetArray);
}
// 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[0]);
}
@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;
}
}

View File

@ -1,31 +0,0 @@
package com.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 ListToStringUnitTest {
@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, "|"));
}
}