[list-ic-contains] Check if a List Contains a String Element While Ignoring Case (#14826)

This commit is contained in:
Kai Yuan 2023-09-27 03:08:30 +02:00 committed by GitHub
parent 36ba51772a
commit ef3c6c0e0b
3 changed files with 60 additions and 0 deletions

View File

@ -0,0 +1,15 @@
<?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-6</artifactId>
<name>core-java-collections-list-6</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</project>

View File

@ -0,0 +1,44 @@
package com.baeldung.lists;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
public class StringListCaseInsensitiveContainsUnitTest {
private final static List<String> THE_LIST = List.of("Game of Thrones", "Forrest Gump", "American Beauty", "Pretty Woman", "Catch Me If You Can");
@Test
void whenUsingContains_thenGetExpectedResult() {
assertFalse(THE_LIST.contains("catch me if you can"));
}
boolean ignoreCaseContainsForLoop(List<String> list, String value) {
for (String e : list) {
if (value.equalsIgnoreCase(e))
return true;
}
return false;
}
@Test
void whenUsingIgnoreCaseContainsForLoop_thenGetExpectedResult() {
assertTrue(ignoreCaseContainsForLoop(THE_LIST, "CATCH me if you CAN"));
assertTrue(ignoreCaseContainsForLoop(THE_LIST, "game of thrones"));
assertFalse(ignoreCaseContainsForLoop(THE_LIST, "The Godfather"));
}
@Test
void whenUsingIgnoreCaseContainsStream_thenGetExpectedResult() {
assertTrue(THE_LIST.stream()
.anyMatch(e -> e.equalsIgnoreCase("CATCH me if you CAN")));
assertTrue(THE_LIST.stream()
.anyMatch("game of thrones"::equalsIgnoreCase));
assertFalse(THE_LIST.stream()
.anyMatch("The Godfather"::equalsIgnoreCase));
}
}

View File

@ -78,6 +78,7 @@
<module>core-java-collections-list</module>
<module>core-java-collections-list-2</module>
<module>core-java-collections-list-3</module>
<module>core-java-collections-list-6</module>
<module>core-java-collections-maps</module>
<module>core-java-collections-maps-2</module>
<module>core-java-collections-maps-3</module>