I am trying to write a method which will return me a code corresponding to a bank product which I need to pass to a web service. I have an array of eligible generic types of products and the input will be a string which will be a specific type of any of the generic types in the array. Let me explain this via the code I already have :
public static void main(String[] args)
{
String[] names = { "Checking", "Savings", "DEMAT", "DEMAT Savings", "Interest Checking" };
String input = "Employee Checking";
int min = Integer.MAX_VALUE;
String maxMatch = null;
for(String name : names)
{
int i = input.indexOf(name);
if(i > -1 && i < min)
{
min = i;
maxMatch = name;
}
}
if(null != maxMatch)
{
System.out.println("Maximum match for " + input + " found at " + maxMatch);
}
}
The above snippet tries to perform a maximum match for the input. So, if I have "Employee Interest Checking" as input, I get match at "Interest Checking" and not just "Checking".
What I want to know is whether is there any way to optimize this snippet further or are there any cases where this code will fail?
If you keep sorted array by string length, you can be sure that first match would give the max match
import java.util.Arrays;
import java.util.Comparator;
public class MaxIndex {
private static String[] names = { "Checking", "Savings", "DEMAT", "DEMAT Savings",
"Interest Checking","Savings Interest Checking","My Employee Savings Interest Checking" };
public static void main(String[] args) {
Arrays.sort(names, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
Integer L1 = o1.length();
return L1.compareTo(o2.length())*-1;
}
});
findMaxMatch("Employee Checking");
findMaxMatch("Employee Savings");
findMaxMatch("Employee Interest Checking");
findMaxMatch("Employee Savings Interest Checking");
findMaxMatch("My Employee Savings Interest Checking");
findMaxMatch("Employee Current");
}
private static void findMaxMatch(String input) {
String maxMatch = maxMatch(input);
if (null != maxMatch) {
System.out.println("Maximum match for '" + input + "' found at '"
+ maxMatch+"'");
}else{
System.out.println("No match for '"+input+"'");
}
}
private static String maxMatch(String input) {
for (String name : names) {
int i = input.indexOf(name);
if (i > -1) {
return name;
}
}
return null;
}
}
Output
Maximum match for 'Employee Checking' found at 'Checking'
Maximum match for 'Employee Savings' found at 'Savings'
Maximum match for 'Employee Interest Checking' found at 'Interest Checking'
Maximum match for 'Employee Savings Interest Checking' found at 'Savings Interest Checking'
Maximum match for 'My Employee Savings Interest Checking' found at 'My Employee Savings Interest Checking'
No match for 'Employee Current'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With