- I have created an Address class*
public class Address {
private long id;
private String organizationName;
private long entId;
private String orgAddress;
private String orgType;
}
And I have created a list which have Address objects inside and i have created an Api using it.
List<Address> list;
public AddressServiceImpl() {
list=new ArrayList<>();
list.add(new Address(1,"Anth",123456,"Time square,NY","Doctor"));
list.add(new Address(2,"carl",12114,"street 16,NY","Staff"));
}
and now i need to search a part of string from the list now and i want to fetch the objects that have **organizationName **as the related String
@Override
public List<Address> searchAddress(String search) {
List<Address> listClone= new ArrayList<>();
for(Address d : list){
if(d.getOrganizationName().toLowerCase() != null && d.getOrganizationName().contains(search.toLowerCase())) {
listClone.add(d);
}
}
return listClone;
}
But when i am searching "Anth" and "anth" it is not giving any response.Please Help!!!
But when i am searching "Anth" and "anth" it is not giving any response.Please Help!!!
CodePudding user response:
Regarding the code
if(d.getOrganizationName().toLowerCase() != null
&& d.getOrganizationName().contains(search.toLowerCase())) {
listClone.add(d);
}
Two issues here:
- your null check is bad. If
d.getOrganizationName()
isnull
(which can apparently happen), callingtoLowerCase
on it will throw aNullPointerException
. - your other part of the check uses
contains
, but you don't usetoLowerCase
on it.
What you want is
if(d.getOrganizationName() != null
&& d.getOrganizationName().toLowerCase().contains(search.toLowerCase())) {
listClone.add(d);
}
CodePudding user response:
you just miss toLower() in d.getOrganizationName() .
public static List searchAddress(String search) {
List<Address> listClone = new ArrayList<>();
for (Address d : AddressServiceImpl()) {
if (d.getOrganizationName() != null
&& d.getOrganizationName().toLowerCase().contains(search.toLowerCase())) {
listClone.add(d);
}
}
return listClone;
}