Java 核心(Core Java)集合中的 List 列表 (第2部分)的内容

This commit is contained in:
YuCheng Hu 2022-05-02 12:21:22 -04:00
parent b77f80f54f
commit 8916057acb
14 changed files with 737 additions and 0 deletions

View File

@ -0,0 +1,15 @@
## Java 核心Core Java集合中的 List 列表 第2部分
This module contains articles about the Java List collection
### Relevant Articles:
- [Check If Two Lists are Equal in Java](https://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
- [A Guide to the Java LinkedList](https://www.baeldung.com/java-linkedlist)
- [Java List UnsupportedOperationException](https://www.baeldung.com/java-list-unsupported-operation-exception)
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
- [Flattening Nested Collections in Java](https://www.baeldung.com/java-flatten-nested-collections)
- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
- [Searching for a String in an ArrayList](https://www.baeldung.com/java-search-string-arraylist)
- [[<-- Prev]](/core-java-modules/core-java-collections-list)[[Next -->]](/core-java-modules/core-java-collections-list-3)

View File

@ -0,0 +1,32 @@
<?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>core-java-collections-list-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-list-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.ossez.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,72 @@
package com.ossez.findastring;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.collections4.IteratorUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class FindAStringInGivenList {
public List<String> findUsingLoopWithRegex(String search, List<String> list) {
List<String> matches = new ArrayList<String>();
String pattern = ".*"+search+".*";
Pattern p = Pattern.compile(pattern);
for(String str: list) {
if (p.matcher(str).matches()) {
matches.add(str);
}
}
return matches;
}
public List<String> findUsingLoop(String search, List<String> list) {
List<String> matches = new ArrayList<String>();
for(String str: list) {
if (str.contains(search)) {
matches.add(str);
}
}
return matches;
}
public List<String> findUsingStream(String search, List<String> list) {
List<String> matchingElements =
list.stream()
.filter(str -> str.trim().contains(search))
.collect(Collectors.toList());
return matchingElements;
}
public List<String> findUsingGuava(String search, List<String> list) {
Iterable<String> result = Iterables.filter(list, Predicates.containsPattern(search));
return Lists.newArrayList(result.iterator());
}
public List<String> findUsingCommonsCollection(String search, List<String> list) {
Iterable<String> result = IterableUtils.filteredIterable(list, new org.apache.commons.collections4.Predicate<String>() {
public boolean evaluate(String listElement) {
return listElement.contains(search);
}
});
return IteratorUtils.toList(result.iterator());
}
}

View File

@ -0,0 +1,67 @@
package com.ossez.java.list;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* Demonstrates the different ways to loop over
* the elements of a list.
*/
public class WaysToIterate {
List<String> countries = Arrays.asList("Germany", "Panama", "Australia");
/**
* Iterate over a list using a basic for loop
*/
public void iterateWithForLoop() {
for (int i = 0; i < countries.size(); i++) {
System.out.println(countries.get(i));
}
}
/**
* Iterate over a list using the enhanced for loop
*/
public void iterateWithEnhancedForLoop() {
for (String country : countries) {
System.out.println(country);
}
}
/**
* Iterate over a list using an Iterator
*/
public void iterateWithIterator() {
Iterator<String> countriesIterator = countries.iterator();
while(countriesIterator.hasNext()) {
System.out.println(countriesIterator.next());
}
}
/**
* Iterate over a list using a ListIterator
*/
public void iterateWithListIterator() {
ListIterator<String> listIterator = countries.listIterator();
while(listIterator.hasNext()) {
System.out.println(listIterator.next());
}
}
/**
* Iterate over a list using the Iterable.forEach() method
*/
public void iterateWithForEach() {
countries.forEach(System.out::println);
}
/**
* Iterate over a list using the Stream.forEach() method
*/
public void iterateWithStreamForEach() {
countries.stream().forEach((c) -> System.out.println(c));
}
}

View File

@ -0,0 +1,13 @@
<?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>

View File

@ -0,0 +1,116 @@
package com.ossez.array.converter;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class ArrayConvertToListUnitTest {
@Test
public void givenAnStringArray_whenConvertArrayToList_thenListCreated() {
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
List<String> flowerList = Arrays.asList(flowers);
assertNotNull(flowerList);
assertEquals(flowerList.size(), 4);
assertEquals(flowerList.get(0), "Ageratum");
assertEquals(flowerList.get(1), "Allium");
assertEquals(flowerList.get(2), "Poppy");
assertEquals(flowerList.get(3), "Catmint");
}
@Test
public void givenAnIntArray_whenConvertArrayToList_thenListWithOneElementCreated() {
int[] primitives = { 1, 2, 3, 4 };
List numbers = Arrays.asList(primitives);
assertNotNull(numbers);
assertEquals(numbers.size(), 1);
assertEquals(numbers.get(0), primitives);
}
@Test(expected = UnsupportedOperationException.class)
public void givenAnStringArray_whenConvertArrayToListAndAddAnElement_thenThrowUnsupportedOperationException() {
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
List<String> flowerList = Arrays.asList(flowers);
assertNotNull(flowerList);
assertEquals(flowerList.size(), 4);
assertEquals(flowerList.get(0), "Ageratum");
assertEquals(flowerList.get(1), "Allium");
assertEquals(flowerList.get(2), "Poppy");
assertEquals(flowerList.get(3), "Catmint");
flowerList.add("Celosia");
}
@Test(expected = UnsupportedOperationException.class)
public void givenAnStringArray_whenConvertArrayToListAndRemoveAnElement_thenThrowUnsupportedOperationException() {
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
List<String> flowerList = Arrays.asList(flowers);
assertNotNull(flowerList);
assertEquals(flowerList.size(), 4);
assertEquals(flowerList.get(0), "Ageratum");
assertEquals(flowerList.get(1), "Allium");
assertEquals(flowerList.get(2), "Poppy");
assertEquals(flowerList.get(3), "Catmint");
flowerList.remove("Poppy");
}
@Test
public void givenAnStringArray_whenCreateListFromArrayAndAddAnElement_thenListOk() {
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
List<String> flowerList = Arrays.asList(flowers);
assertNotNull(flowerList);
assertEquals(flowerList.size(), 4);
assertEquals(flowerList.get(0), "Ageratum");
assertEquals(flowerList.get(1), "Allium");
assertEquals(flowerList.get(2), "Poppy");
assertEquals(flowerList.get(3), "Catmint");
List<String> newflowerList = new ArrayList<>(flowerList);
assertNotNull(newflowerList);
assertEquals(newflowerList.size(), 4);
assertEquals(newflowerList.get(0), "Ageratum");
assertEquals(newflowerList.get(1), "Allium");
assertEquals(newflowerList.get(2), "Poppy");
assertEquals(newflowerList.get(3), "Catmint");
newflowerList.add("Celosia");
assertEquals(newflowerList.size(), 5);
assertEquals(newflowerList.get(4), "Celosia");
}
@Test
public void givenAnStringArray_whenIterateArrayAndAddTheElementsToNewListAndAddAnElement_thenListOk() {
String[] flowers = { "Ageratum", "Allium", "Poppy", "Catmint" };
List<String> flowerList = new ArrayList<>();
for(String flower: flowers) {
flowerList.add(flower);
}
assertNotNull(flowerList);
assertEquals(flowerList.size(), 4);
assertEquals(flowerList.get(0), "Ageratum");
assertEquals(flowerList.get(1), "Allium");
assertEquals(flowerList.get(2), "Poppy");
assertEquals(flowerList.get(3), "Catmint");
flowerList.add("Celosia");
assertEquals(flowerList.size(), 5);
assertEquals(flowerList.get(4), "Celosia");
}
}

View File

@ -0,0 +1,88 @@
package com.ossez.findItems;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
public class FindItemsBasedOnOtherStreamUnitTest {
private List<Employee> employeeList = new ArrayList<Employee>();
private List<Department> departmentList = new ArrayList<Department>();
@Test
public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() {
Integer expectedId = 1002;
populate(employeeList, departmentList);
List<Employee> filteredList = employeeList.stream()
.filter(empl -> departmentList.stream()
.anyMatch(dept -> dept.getDepartment()
.equals("sales") && empl.getEmployeeId()
.equals(dept.getEmployeeId())))
.collect(Collectors.toList());
assertEquals(expectedId, filteredList.get(0)
.getEmployeeId());
}
private void populate(List<Employee> EmplList, List<Department> deptList) {
Employee employee1 = new Employee(1001, "empl1");
Employee employee2 = new Employee(1002, "empl2");
Employee employee3 = new Employee(1003, "empl3");
Collections.addAll(EmplList, employee1, employee2, employee3);
Department department1 = new Department(1002, "sales");
Department department2 = new Department(1003, "marketing");
Department department3 = new Department(1004, "sales");
Collections.addAll(deptList, department1, department2, department3);
}
}
class Employee {
private Integer employeeId;
private String employeeName;
Employee(Integer employeeId, String employeeName) {
super();
this.employeeId = employeeId;
this.employeeName = employeeName;
}
Integer getEmployeeId() {
return employeeId;
}
public String getEmployeeName() {
return employeeName;
}
}
class Department {
private Integer employeeId;
private String department;
Department(Integer employeeId, String department) {
super();
this.employeeId = employeeId;
this.department = department;
}
Integer getEmployeeId() {
return employeeId;
}
String getDepartment() {
return department;
}
}

View File

@ -0,0 +1,62 @@
package com.ossez.findastring;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
public class FindAStringInListUnitTest {
private static List<String> list = new ArrayList<>();
static {
list.add("Jack and Jill");
list.add("James and Sarah");
list.add("Sam and Louise");
list.add("Jack");
list.add("");
}
private static FindAStringInGivenList findAStringInGivenList = new FindAStringInGivenList();
@Test
public void givenAString_whenFoundUsingLoopWithRegex_thenReturnList() {
List matchingElements = findAStringInGivenList.findUsingLoopWithRegex("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
@Test
public void givenAString_whenFoundUsingLoop_thenReturnList() {
List matchingElements = findAStringInGivenList.findUsingLoop("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
@Test
public void givenAString_whenFoundUsingStream_thenReturnList(){
List matchingElements = findAStringInGivenList.findUsingStream("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
@Test
public void givenAString_whenFoundUsingCommonsCollection_thenReturnList(){
List matchingElements = findAStringInGivenList.findUsingCommonsCollection("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
@Test
public void givenAString_whenFoundUsingGuava_thenReturnList(){
List matchingElements = findAStringInGivenList.findUsingGuava("Jack", list);
assertEquals(2, matchingElements.size());
assertEquals("Jack and Jill", matchingElements.get(0));
assertEquals("Jack", matchingElements.get(1));
}
}

View File

@ -0,0 +1,23 @@
package com.ossez.java.list;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ListAssertJUnitTest {
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
private final List<String> list3 = Arrays.asList("1", "2", "4", "3");
@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
assertThat(list1).isEqualTo(list2).isNotEqualTo(list3);
assertThat(list1.equals(list2)).isTrue();
assertThat(list1.equals(list3)).isFalse();
}
}

View File

@ -0,0 +1,47 @@
package com.ossez.java.list;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.stream.Collectors;
public class ListJUnitTest {
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
private final List<String> list3 = Arrays.asList("1", "2", "4", "3");
@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
Assert.assertEquals(list1, list2);
Assert.assertNotSame(list1, list2);
Assert.assertNotEquals(list1, list3);
}
@Test
public void whenIntersection_ShouldReturnCommonElements() throws Exception {
List<String> list = Arrays.asList("red", "blue", "blue", "green", "red");
List<String> otherList = Arrays.asList("red", "green", "green", "yellow");
Set<String> commonElements = new HashSet(Arrays.asList("red", "green"));
Set<String> result = list.stream()
.distinct()
.filter(otherList::contains)
.collect(Collectors.toSet());
Assert.assertEquals(commonElements, result);
Set<String> inverseResult = otherList.stream()
.distinct()
.filter(list::contains)
.collect(Collectors.toSet());
Assert.assertEquals(commonElements, inverseResult);
}
}

View File

@ -0,0 +1,22 @@
package com.ossez.java.list;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
public class ListTestNgUnitTest {
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
private final List<String> list3 = Arrays.asList("1", "2", "4", "3");
@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
assertEquals(list1, list2);
assertNotSame(list1, list2);
assertNotEquals(list1, list3);
}
}

View File

@ -0,0 +1,71 @@
package com.ossez.java.list;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.junit.Test;
public class WaysToIterateUnitTest {
List<String> globalCountries = new ArrayList<String>();
List<String> europeanCountries = Arrays.asList("Germany", "Panama", "Australia");
@Test
public void whenIteratingUsingForLoop_thenReturnThreeAsSizeOfList() {
for (int i = 0; i < europeanCountries.size(); i++) {
globalCountries.add(europeanCountries.get(i));
}
assertEquals(globalCountries.size(), 3);
globalCountries.clear();
}
@Test
public void whenIteratingUsingEnhancedForLoop_thenReturnThreeAsSizeOfList() {
for (String country : europeanCountries) {
globalCountries.add(country);
}
assertEquals(globalCountries.size(), 3);
globalCountries.clear();
}
@Test
public void whenIteratingUsingIterator_thenReturnThreeAsSizeOfList() {
Iterator<String> countriesIterator = europeanCountries.iterator();
while (countriesIterator.hasNext()) {
globalCountries.add(countriesIterator.next());
}
assertEquals(globalCountries.size(), 3);
globalCountries.clear();
}
@Test
public void whenIteratingUsingListIterator_thenReturnThreeAsSizeOfList() {
ListIterator<String> countriesIterator = europeanCountries.listIterator();
while (countriesIterator.hasNext()) {
globalCountries.add(countriesIterator.next());
}
assertEquals(globalCountries.size(), 3);
globalCountries.clear();
}
@Test
public void whenIteratingUsingForEach_thenReturnThreeAsSizeOfList() {
europeanCountries.forEach(country -> globalCountries.add(country));
assertEquals(globalCountries.size(), 3);
globalCountries.clear();
}
@Test
public void whenIteratingUsingStreamForEach_thenReturnThreeAsSizeOfList() {
europeanCountries.stream().forEach((country) -> globalCountries.add(country));
assertEquals(globalCountries.size(), 3);
globalCountries.clear();
}
}

View File

@ -0,0 +1,59 @@
package com.ossez.java.listInitialization;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.extern.java.Log;
import org.junit.Assert;
import org.junit.Test;
@Log
public class ListInitializationUnitTest {
@Test
public void givenAnonymousInnerClass_thenInitialiseList() {
List<String> cities = new ArrayList() {
{
add("New York");
add("Rio");
add("Tokyo");
}
};
Assert.assertTrue(cities.contains("New York"));
}
@Test
public void givenArraysAsList_thenInitialiseList() {
List<String> list = Arrays.asList("foo", "bar");
Assert.assertTrue(list.contains("foo"));
}
@Test(expected = UnsupportedOperationException.class)
public void givenArraysAsList_whenAdd_thenUnsupportedException() {
List<String> list = Arrays.asList("foo", "bar");
list.add("baz");
}
@Test
public void givenArraysAsList_whenCreated_thenShareReference() {
String[] array = { "foo", "bar" };
List<String> list = Arrays.asList(array);
array[0] = "baz";
Assert.assertEquals("baz", list.get(0));
}
@Test
public void givenStream_thenInitializeList() {
List<String> list = Stream.of("foo", "bar")
.collect(Collectors.toList());
Assert.assertTrue(list.contains("foo"));
}
}

View File

@ -0,0 +1,50 @@
package com.ossez.list.flattennestedlist;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.hamcrest.collection.IsIterableContainingInOrder;
import org.junit.Test;
public class FlattenNestedListUnitTest {
private List<List<String>> lol = asList(asList("one:one"), asList("two:one", "two:two", "two:three"), asList("three:one", "three:two", "three:three", "three:four"));
@Test
public void givenNestedList_thenFlattenImperatively() {
List<String> ls = flattenListOfListsImperatively(lol);
assertNotNull(ls);
assertTrue(ls.size() == 8);
// assert content
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
}
@Test
public void givenNestedList_thenFlattenFunctionally() {
List<String> ls = flattenListOfListsStream(lol);
assertNotNull(ls);
assertTrue(ls.size() == 8);
// assert content
assertThat(ls, IsIterableContainingInOrder.contains("one:one", "two:one", "two:two", "two:three", "three:one", "three:two", "three:three", "three:four"));
}
private <T> List<T> flattenListOfListsImperatively(List<List<T>> list) {
List<T> ls = new ArrayList<>();
list.forEach(ls::addAll);
return ls;
}
private <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
}