0

We have an array list which holds TestVo objects. TestVo object have "blockNo, buildingName, etc" variables with getter and setters. We are setting the values and adding that object to the list. Now we need to remove the object contains null value from the list. Sample Code:

List <TestVo> listOfBranches = new ArrayList<TestVo>(); TestVo obj1 = new TestVo(); obj1.setBlockNo("1-23"); obj1.setBuildingName(null); TestVo obj2 = new TestVo(); obj2.setBlockNo(null); obj2.setBuildingName("test"); TestVo obj3 = new TestVo(); obj3.setBlockNo("4-56"); obj3.setBuildingName("test, Ind"); listOfBranches.add(obj1); listOfBranches.add(obj2); listOfBranches.add(obj3); 

So finally how can we remove the object contains null value from the list.

3
  • 1
    Iterate over all of them, check all their members, remove if null occurs. Commented Dec 17, 2015 at 10:07
  • Thank you for your reply. We have done that for now. I have posted here to know any other possibilities to simplify this logic without iteration. Commented Dec 17, 2015 at 10:11
  • You need to iterate over the elements of the list, either implicitly or explicitly. Commented Dec 17, 2015 at 10:15

1 Answer 1

1

Using the Java 8 stream API,

 listOfBranches = listOfBranches .stream() .filter(candidate -> candidate.getBlockNo() != null) .collect(Collectors.toList()); 

could do the work for you.

Otherwise, use an iterator:

 Iterator it = myList.iterator(); while(it.hasNext()) { if (it.next().getBlockNo() == null) { it.remove(); } } 
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you loan. But we are not supposed to change the jdk version for now.
Like getBlockNo we have max 78 variables and checking for 78 is ok. But same kind of logic needs to be done for many other places as well. SO i feel code messy
Then simply add a method inside your object, e.g. isValid, and use always this method to filter the objects.
Or perhaps use a map instead of instance variables, then you can handle everything way much better.
Thanks Loan, it will works with maps. But the problem is we have been suggested to use List among the team.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.