core-java-collections-conversions 内容进行布局

This commit is contained in:
YuCheng Hu
2023-05-09 17:05:33 -04:00
parent 2c9bdbe6e0
commit 43097ff34b
37 changed files with 31 additions and 1085 deletions
+6 -1
View File
@@ -2,6 +2,7 @@
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
@@ -21,18 +22,22 @@
<module name="spring-data-jpa-repo-2" />
<module name="core-java-streams" />
<module name="core-java-io" />
<module name="java-collections-conversions" />
<module name="core-java-8-2" />
<module name="discourse" />
<module name="spring-data-redis" />
<module name="core-java" />
<module name="core-java-collections-list-2" />
<module name="core-java-collections-list-3" />
<module name="core-java-collections-conversions-2" />
<module name="core-java-8" />
<module name="core-java-collections-3" />
<module name="core-java-collections-2" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel>
<module name="java-collections-conversions" target="11" />
<module name="java-collections-conversions-2" target="11" />
</bytecodeTargetLevel>
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
+2
View File
@@ -13,6 +13,8 @@
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-2/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-3/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-3/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-conversions-2/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-conversions-2/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-conversions/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-conversions/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/core-java-modules/core-java-collections-list-2/src/main/java" charset="UTF-8" />
@@ -0,0 +1,14 @@
## Java 集合(Collections)相关文章和实例
本模块中的内容包含有 Java 集合(Collections)和数组(arrays)中进行转换。
### 相关文章
- [Java Array 和 String 的转换](https://www.ossez.com/t/java-array-string/13685)
- [Mapping Lists with ModelMapper](https://www.baeldung.com/java-modelmapper-lists)
- [Converting List to Map With a Custom Supplier](https://www.baeldung.com/list-to-map-supplier)
- [Arrays.asList vs new ArrayList(Arrays.asList())](https://www.baeldung.com/java-arrays-aslist-vs-new-arraylist)
- [Iterate Over a Set in Java](https://www.baeldung.com/java-iterate-set)
- [Convert a List of Integers to a List of Strings](https://www.baeldung.com/java-convert-list-integers-to-list-strings)
- [Combining Two Lists Into a Map in Java](https://www.baeldung.com/java-combine-two-lists-into-map)
- More articles: [[<-- prev]](../core-java-collections-conversions)
@@ -3,16 +3,16 @@
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>java-collections-conversions-2</artifactId>
<artifactId>core-java-collections-conversions-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>java-collections-conversions-2</name>
<name>core-java-collections-conversions-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez</groupId>
<artifactId>parent-java</artifactId>
<groupId>com.ossez.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.2-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
<relativePath>../pom.xml</relativePath>
</parent>
<dependencies>
@@ -1,9 +1,10 @@
## Java 集合(Collections)相关文章和实例
本模块中的内容包含有 Java 集合(Collections)转换相关的方法。
本模块中的内容包含有 Java 集合(Collections)和数组(arrays)中进行转换。
### 相关文章
- [Converting between an Array and a List in Java](https://www.baeldung.com/convert-array-to-list-and-list-to-array)
- [Java 如何在 Array 和 List 之间进行转换](https://www.ossez.com/t/java-array-list/14416)
- [Converting Between an Array and a Set in Java](https://www.baeldung.com/convert-array-to-set-and-set-to-array)
- [Java 把 Map 的值(Value)转换为 Array, List 或 Set](https://www.ossez.com/t/java-map-value-array-list-set/14388)
- [Converting a List to String in Java](https://www.baeldung.com/java-list-to-string)
+1
View File
@@ -25,6 +25,7 @@
<module>core-java-collections-2</module>
<module>core-java-collections-3</module>
<module>core-java-collections-conversions</module>
<module>core-java-collections-conversions-2</module>
<module>core-java-collections-list</module>
<module>core-java-collections-list-2</module>
<module>core-java-collections-list-3</module>
-12
View File
@@ -1,12 +0,0 @@
## Java Collections Cookbooks and Examples
This module contains articles about conversions among Collection types and arrays in Java.
### Relevant Articles:
- [Java Array 和 String 的转换](https://www.ossez.com/t/java-array-string/13685)
- [Mapping Lists with ModelMapper](https://www.baeldung.com/java-modelmapper-lists)
- [Converting List to Map With a Custom Supplier](https://www.baeldung.com/list-to-map-supplier)
- [Java Arrays.asList 和 new ArrayList(Arrays.asList()) 的对比](https://www.ossez.com/t/java-arrays-aslist-new-arraylist-arrays-aslist/13680)
- [Iterate Over a Set in Java](https://www.baeldung.com/java-iterate-set)
- More articles: [[<-- prev]](../java-collections-conversions)
-16
View File
@@ -1,16 +0,0 @@
## Java 集合模块和实例(Core Java)
本模块中的内容包括有如何在 Java 的集合和数组(arrays)中进行转换。
### 相关文章:
- [Java 如何在 Array 和 List 之间进行转换](https://www.ossez.com/t/java-array-list/14416)
- [Converting between an Array and a Set in Java](https://www.baeldung.com/convert-array-to-set-and-set-to-array)
- [Convert a Map to an Array, List or Set in Java](https://www.baeldung.com/convert-map-values-to-array-list-set)
- [Converting a List to String in Java](https://www.baeldung.com/java-list-to-string)
- [How to Convert List to Map in Java](https://www.baeldung.com/java-list-to-map)
- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist)
- [Java 8 Collectors toMap](https://www.baeldung.com/java-collectors-tomap)
- [Converting Iterable to Collection in Java](https://www.baeldung.com/java-iterable-to-collection)
- [Converting Iterator to List](https://www.baeldung.com/java-convert-iterator-to-list)
- More articles: [[next -->]](../java-collections-conversions-2)
-52
View File
@@ -1,52 +0,0 @@
<?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>java-collections-conversions</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>java-collections-conversions</name>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.2-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>java-collections-conversions</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
</properties>
</project>
@@ -1,48 +0,0 @@
package com.ossez.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;
}
}
@@ -1,30 +0,0 @@
package com.ossez.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));
}
}
@@ -1,52 +0,0 @@
package com.ossez.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);
}
}
@@ -1,27 +0,0 @@
package com.ossez.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;
}
}
@@ -1,43 +0,0 @@
package com.ossez.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;
}
}
@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -1,51 +0,0 @@
package com.ossez.arrayconversion;
import org.assertj.core.api.ListAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* <p>
* ArrayToListConversionUnitTest
* <ul>
* <li>@see <a href= "https://www.ossez.com/t/java-arrays-aslist-new-arraylist-arrays-aslist/13680">Arrays.asList vs new ArrayList(Arrays.asList())</a>
* </li>
* </ul>
* </p>
*
* @author YuCheng
*/
/*Line 1
Line 2
Line 3*/
public class ArrayToListConversionUnitTest {
@Test(expected = UnsupportedOperationException.class)
public void givenAnArray_whenConvertingToList_returnUnmodifiableListUnitTest() {
String[] stringArray = new String[]{"A", "B", "C", "D"};
List<String> stringList = Arrays.asList(stringArray);
stringList.set(0, "E");
assertThat(stringList).containsExactly("E", "B", "C", "D");
assertThat(stringArray).containsExactly("E", "B", "C", "D");
stringList.add("F");
}
@Test
public void givenAnArray_whenConvertingToList_returnModifiableListUnitTest() {
String[] stringArray = new String[]{"A", "B", "C", "D"};
List<String> stringList = new ArrayList<>(Arrays.asList(stringArray));
stringList.set(0, "E");
assertThat(stringList).containsExactly("E", "B", "C", "D");
assertThat(stringArray).containsExactly("A", "B", "C", "D");
stringList.add("F");
assertThat(stringList).containsExactly("E", "B", "C", "D", "F");
}
}
@@ -1,53 +0,0 @@
package com.ossez.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"));
}
}
@@ -1,145 +0,0 @@
package com.ossez.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;
}
}

Some files were not shown because too many files have changed in this diff Show More