Not able to remove null from a list in Java [duplicate] - java

This question already has answers here:
Why do I get a NullPointerException when comparing a String with null?
(4 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 days ago.
I have a list of a bean class newSRMAPIResponseBeanList wherein I am always getting a null object at last which I am trying to remove but it is resulting in null pointer exception if I handle the exception, it is not removing that null value. Below is my code.
for (int i = 0; i < newSRMAPIResponseBeanList.size(); i++) {
try {
if (newSRMAPIResponseBeanList.get(i).getCompanyId().equals(null)) {
newSRMAPIResponseBeanList.remove(i);
}
}catch(Exception e) {
e.printStackTrace();
}
}
In the if condition itself it is failing. I want to remove the null value of company ID. Actually newSRMAPIResponseBeanList is a list of List<NewSRMAPIResponseBean> newSRMAPIResponseBeanList = new ArrayList<>(); and the bean class is as follows.
public class NewSRMAPIResponseBean {
private String companyId;
private String investmentId;
private String performanceId;
private List<String> values;
}
Is there any way I can remove that null value? I also tried using Java streams as follows.
List<NewSRMAPIResponseBean> finalList=newSRMAPIResponseBeanList.parallelStream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
This too did not work.

I want to remove the null value of company ID.
I presume you mean remove the list element if the Id is null. So It's not the bean that is null, it is the companyId. Assuming you have getters, try it like this. If the Id is not null, let it pass thru.
List<NewSRMAPIResponseBean> finalList=newSRMAPIResponseBeanList.parallelStream()
.filter(bean->bean.getCompanyId() != null)
.collect(Collectors.toList());
You can also do it in a simple loop.
To avoid a ConurrentModificationException, use an iterator.
Iterator<NewSRMAPIResponseBean> iter = newSRMAPIResponseBeanList.iterator();
while (iter.hasNext()) {
if (iter.next().getCompanyId() == null) {
iter.remove();
}
}

Related

search is not working in Arraylist due to case sensitivity [duplicate]

This question already has answers here:
Ignore case for 'contains' for a string in Java [duplicate]
(6 answers)
Closed 20 days ago.
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!!!
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() is null (which can apparently happen), calling toLowerCase on it will throw a NullPointerException.
your other part of the check uses contains, but you don't use toLowerCase on it.
What you want is
if(d.getOrganizationName() != null
&& d.getOrganizationName().toLowerCase().contains(search.toLowerCase())) {
listClone.add(d);
}
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;
}

Check if String is null from a Class [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
i know that my question is a duplicate of some question here before, i tried every solution that i see from that, but no solution work for me
i have a class named FilingModel and a method name getReason, i always get a null value to my tvReason TextView
public class FilingAdapter extends RecyclerView.Adapter<FilingAdapter.FilingHolder> {
List<FilingModel> lists;
#Override
public void onBindViewHolder(#NonNull FilingHolder holder, int position) {
FilingModel model = lists.get(position);
holder.tvReason.setText(model.getReason());
}
}
public class FilingModel {
private String reason;
public FilingModel(String reason) {
this.reason = reason;
}
public String getReason() {
if ( reason.isEmpty() || TextUtils.isEmpty(reason) || reason.equals(null)) {
reason = "-";
}
return reason;
}
}
String checks for null are rather straight forward (once you have done it):
First you want to check if the instance is null (otherwise all further manipulation might fail):
if(reason == null)
Then you want to check if it is empty as you already did it but maybe you want to trim it first (to remove all whitespaces):
if(reason == null || reason.trim().isEmpty())
as you can see you can chain the conditions with or since Java will stop evaluating the conditions once one of them was found true . So if your string is null, Java will not evaluate if it is empty.
And that's all you need, null and isEmpty (and optionally with a trim())
public String getReason() {
if(reason==null || reason.trim().isEmpty()){
reason = "-";
}
return reason;
}
Give type to your variable reason. For example String.
private String reason;
+
if(reason == null)

How to get around array.equals(otherArray) evaluating to null? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm trying to make a for loop that loops through an array, comparing the user input to each object using a method called getID() that returns the stored user IDs for various employees. The data is not saved between runs, so on the first loop, all objects (I believe) should be null. With that being said, I get a nullPointerException on the line that's supposed to compare the strings retrieved by getID() and the userInput string. The array is initialized as follows:
Salesperson[] staffList;
staffList = new Salesperson[20];
Here is the loop in question, the if statement is the line that throws the NPE:
for(i = 0; i < staffList.length; i++)
{
if(staffList[i].getID().equals(idNum))
{
duplicateID = true;
}
}
Here is the class for the Salesperson array:
public class Salesperson
{
private String name;
private String idNum;
private double annSales;
//Various getter and setter methods here
}
If I missed anything please let me know. I've used Stack Overflow in the past but have never asked a question myself. I've tried searching around here but have yet to find anything that helped me. Thanks in advance!
You can update your code something like below to avoid NPE.
Salesperson[] staffList;
staffList = new Salesperson[20];
for(int i = 0; i < staffList.length; i++)
{
Salesperson salesPerson = staffList[i]; // staffList[i] i.e salesPerson = null.... null.getId throws NPE.
System.out.println("sales =" + sales); // sales = null
if(sales != null) {
if (sales.getId().equals(idNum)) {
//Do something..
}
}
}

Concurrent Modification exception when i compile my code, [duplicate]

This question already has answers here:
How to modify a Collection while iterating using for-each loop without ConcurrentModificationException? [duplicate]
(4 answers)
How to add element in List while iterating in java?
(7 answers)
Closed 6 years ago.
I've been given this exercise to do and I'm struggling to understand why I keep getting concurrent modification error when I compile my code.
"If the list contains a film with a title that matches the parameter
title then update it's length and genre. If no match is found create a
new film and add it to the list."
I've managed to check if there's a match for title however when there isn't one I'm unable to successfully add a new film to my array. Here's the code I wrote:
public void updateLengthAndGenre(String title, int length, String genre) {
ArrayList<Film> output = new ArrayList<>();
boolean found = false;
for (Film film : films) {
if (film.getTitle().equals(title)) {
found = true;
film.setGenre(genre);
film.setLength(length);
}
}
for (Film film : films) {
if (!found) {
films.add(new Film(title, length, genre));
}
}
}
Can someone explain why I keep getting this error and also give me some advice how to remedy it?
The reason you're getting this exceotion is because you're trying to simultaneously add to a collection while iterating over it. You cannot do this. In your case, it doesn't seem like you actually even have to do this at all.
public void updateLengthAndGenre(String title, int length, String genre) {
ArrayList<Film> output = new ArrayList<>();
for (Film film : films) {
if (film.getTitle().equals(title)) {
film.setGenre(genre);
film.setLength(length);
return;
}
}
films.add(new Film(title, length, genre)); // synchronize if you're multithreading
}
This has the same effect. If you absolutely need to add to a collection while iterating, you can use a java.util.ListIterator.
ListIterator<Film> filmIter = films.listIterator();
while(filmIter.hasNext()){
if( /* some condition */){
fillmIter.add(new Film(title, length, genre));
}
filmIter.next(); // example only.
}

Nullpointer exception for Long variable [duplicate]

This question already has answers here:
Hibernate Parameter value [568903] did not match expected type [java.lang.Long]
(3 answers)
Closed 9 years ago.
I have the following code
private Long projectNumber; // with getters and setters
and when I am checking whether projectNumber is null or not, I am getting null pointer exception at the if condition
if(selected.getProjectNumber()!=null){
// do something
}
What could be the reason for this even though Long is a wrapper class.
If I change projectNumber from Long to String, it works fine.
Update 1
private Project selected = new Project();
public Project getSelected() {
return selected;
}
public void setSelected(Project selected) {
this.selected = selected;
}
I am getting selected value in ManagedBean of JSF in the following method
public void onRowSelect(SelectEvent event) {
}
projectNo getters and setters
public Long getProjectNo() {
return projectNo;
}
public void setProjectNo(Long projectNo) {
this.projectNo = projectNo;
}
The problem you have is because selected is null, projectNumber. Change the check to something like:
if(selected != null && selected.getProjectNumber()!=null){
// do something
}
Or alternatively add a separate check for selected above.
If you get an NPE here:
if(selected.getProjectNumber()!=null){
and all getProjectNumber() does is return projectNumber, this strongly indicates that selected is null.
the problem is that selected is null. Check it like:
if(selected != null && selected.getProjectNumber()!=null){
// do something
} else {
// here: selected = null OR projectNumber of selected is null
}
did you check if selected is null
you can do the following
if(null != selected)
{
if(null != selected.getProjectNumber())
{
// do something
}
}
Your object selected is apparently null, try to do:
if ((selected != null) && (selected.getProjectNumber()!=null)){
// do something
}
From what you posted, it sems that the problem is that the object referred by the selected variable is null. You have to check that too:
if(selected !=null && selected.getProjectNumber()!=null){
// do something
}
Explanation: Doing it this way, as the boolean AND (and the OR) operator evaluates only the left condition if it is false, not touching the right side, you won't get a NullPointerExceptyion anymore.
EDIT As OP mentioned that by changing the variable to String the problem is not encountered, as 0xCAFEBABE's suggestion implies, the same error might be possible if the getter returns (or somehow internally uses) a simple long value instead of a Long object, and the value of the variable is null:
/** error getter */
public long getProjectNumber() {
//this would trz to convert null, but what will it convert to? A NullPointerExecption...
return projectNumber;
}

Categories

Resources