BAEL-7308: Comparing One String with Multiple Values in One Expression in Java

This commit is contained in:
parthiv39731 2023-12-06 14:12:25 +05:30
parent 3a8bae0c8e
commit 8ad1043d55
2 changed files with 24 additions and 4 deletions

View File

@ -1,6 +1,7 @@
package com.baeldung.compareany;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@ -31,12 +32,12 @@ public class CompareAnyBenchmark {
@Benchmark
public boolean compareWithAnyUsingStringUtils() {
return StringUtils.containsAny(fruit, groupOfFruits);
return StringUtils.equalsAny(fruit, groupOfFruits);
}
@Benchmark
public boolean compareWithAnyCaseInsensitiveUsingStringUtils() {
return StringUtils.containsAnyIgnoreCase(fruit, groupOfFruits);
return StringUtils.equalsAnyIgnoreCase(fruit, groupOfFruits);
}
@Benchmark
@ -44,6 +45,11 @@ public class CompareAnyBenchmark {
return Set.of(groupOfFruits).contains(fruit);
}
@Benchmark
public boolean compareWithAnyUsingList() {
return List.of(groupOfFruits).contains(fruit);
}
@Benchmark
public boolean compareWithAnyUsingRegularExpression() {
return fruit.matches(String.join("|", groupOfFruits));

View File

@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.ArrayUtils;
@ -74,6 +75,15 @@ public class CompareAnyUnitTest {
assertFalse(compareWithAnyUsingSet(notPresentString, "Mango", "Papaya", "Pineapple", "Apple"));
}
@Test
void givenStrings_whenCompareUsingList_thenSuccess() {
String presentString = "Apple";
String notPresentString = "Avocado";
assertTrue(compareWithAnyUsingList(presentString, "Mango", "Papaya", "Pineapple", "Apple"));
assertFalse(compareWithAnyUsingList(notPresentString, "Mango", "Papaya", "Pineapple", "Apple"));
}
@Test
void givenStrings_whenCompareUsingRegularExpression_thenSuccess() {
String presentString = "Apple";
@ -102,17 +112,21 @@ public class CompareAnyUnitTest {
}
private boolean compareWithAnyUsingStringUtils(String str, String ... strs) {
return StringUtils.containsAny(str, strs);
return StringUtils.equalsAny(str, strs);
}
private boolean compareWithAnyCaseInsensitiveUsingStringUtils(String str, String ... strs) {
return StringUtils.containsAnyIgnoreCase(str, strs);
return StringUtils.equalsAnyIgnoreCase(str, strs);
}
private boolean compareWithAnyUsingSet(String str, String ... strs) {
return Set.of(strs).contains(str);
}
private boolean compareWithAnyUsingList(String str, String ... strs) {
return List.of(strs).contains(str);
}
private boolean compareWithAnyUsingRegularExpression(String str, String ... strs) {
return str.matches(String.join("|", strs));
}