The Sample Code which needs a solution?
public class TestJJava {
public static void main(String[] args) {
// TODO Auto-generated method stub
You aren't currently comparing the first three characters because subList
doesn't actually apply a substring function (here it copies the list as is). You can also initialize your List
more efficiently (and you should program to the List
interface). I would stream()
it and map
each element using String.substring
and anyMatch
. Like,
String abc = "123XXXXX0";
List<String> lstValues = new ArrayList<>(List.of("111XXXX1", "122XXX1", "123XXXX1"));
if (lstValues.stream().map(x -> x.substring(0, 3)).anyMatch(abc.substring(0, 3)::equals)) {
System.out.println("**** Match Found ***");
} else {
System.out.println("**** No Match Found ****");
}
Which outputs
**** Match Found ***
List.contain(Object o) checks if the "object" is in the list or not . In your case the objects those are in the List is String and they are "111XXXX1" , "122XXX1" and "122XXX1" . So if the following will return true only
lstValues.contain("111XXXX1")
--> true
lstValues.contain("122XXX1")
--> true
lstValues.contain("122XXX1")
--> true
But if you do the following it will return false :
lstValues.contain("123") --> false .
Here is what javadoc says for List.contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
So you can see it determines if the object is equal or not . So none of the items in the ArrayList matches to "123" . Therefore you will get a "No Match Found"
This is what you are supposed to do.
String first3 = abc.substring(0,3);
boolean found = false;
for (String s : lstValues) {
if (s.startsWith(first3)) {
found = true;
break;
}
}
if (found) {
System.out.println("**** Match Found ***");
} else {
System.out.println("**** No Match Found ****");
}
Go through the list checking each entry until you find a match.
java 1.7
try this ..
`public static void main(String[] args) {
String abc = "123XXXXX0";
ArrayList<String> lstValues = new ArrayList<String>();
lstValues.add("111XXXX1");
lstValues.add("122XXX1");
lstValues.add("123XXXX1");
boolean found = false;
for (String temp : lstValues.subList(0, 3)) {
if (temp.contains(abc.substring(0, 3))) {
found = true;
break;
}
}
if (found) {
System.out.println("**** Match Found ***");
} else {
System.out.println("**** No Match Found ****");
}
}`
You are not comparing the full String
in the list but rather a substring of one of strings in the list.
You will have to loop through the list and check with each String
individually.
String temp = abc.substring(0,3);
boolean flag = true;
for(String value: lstValues.subList(0, 3))
if(value.contains(temp)) // or if(value.indexOf(temp) != -1)
{
System.out.println("**** Match Found ****");
flag = false;
break;
}
if(flag)
System.out.println("**** No Match Found ****");