Refactoring this Java code if String contains any of these capabilities?
I need to check if a string does not contain any of the following lines:
MNC BRA LEB MAR RVK WAY GLZ WWW HYB
My current code:
if(selectedLocation.equals("OTH"))
{
if(!currentClassLocation.equals("MNC") &&
!currentClassLocation.equals("BRA") &&
!currentClassLocation.equals("LEB") &&
!currentClassLocation.equals("MAR") &&
!currentClassLocation.equals("RVC") &&
!currentClassLocation.equals("WAY") &&
!currentClassLocation.equals("GLZ") &&
!currentClassLocation.equals("WWW") &&
!currentClassLocation.equals("HYB"))
{
//Awesome, I need this string! I operate on it here.
}
}
In short, I cannot use a for-loop. Is there a way to check if a string contains none of these without iterating?
+3
source to share
8 answers
Try adding these lines to Set, then find with contains which will be O (c):
public class Filter {
Set<String> exclusionSet = new HashSet<String>();
public Filter( String... excludes ) {
for( String exclusion : excludes ) {
exclusionSet.add( exclusion );
}
}
public boolean exclude( String src ) {
return exclusionSet.contains( src );
}
public static void main( String[] args ) {
Filter filter = new Filter( "MNC BRA LEB MAR RVC WAY GLZ WWW HYB".split(" ") );
for( String arg : args ) {
System.out.println( arg + " is excluded? " + filter.exclude( arg ) );
}
}
}
+2
source to share
Try a variation (using your lines):
Pattern pattern = Pattern.compile("(.*(AIN|BIN|CIN|Blam).*)*");
Matcher matcher = pattern.matcher(string_to_test);
Check out the regex java templates here: Java Regex Tester
0
source to share
If you want to use for-loop you can just use the variable
String[] data = {"BRA","LEB","MAR","RVC","WAY","GLZ","WWW","HYB"};
if(selectedLocation.equals("OTH"))
{
boolean chk = false;
for(int i = 0; i < data.length; i++)
chk |= currentClassLocation.equals(data[i]);
if(!chk){
//Awesome, I need this string! I operate on it here.
}
}
0
source to share
You can also use this if you don't want to manually add installation details.
import java.util.Arrays;
public class StringFind {
public static void main(String[] args) {
String stringtotest = "MNC";
String dataString = "MNC BRA LEB MAR RVC WAY GLZ WWW HYB";
String[] dataArray= dataString.split(" ");
Arrays.sort(dataArray); // You can omit this if data is already sorted.
if(Arrays.binarySearch(dataArray, stringtotest)<0){
System.out.println("Does not Exists");
}else{
System.out.println("Exists");
}
}
}
0
source to share