Search code examples
javagroovy

Retrieving only latest record in iteration after adding multiple values to list using Java


I'm trying to add multiple records to a list and iterate. But it's displaying only latest records added.

Here is my code

List<ExportBean> exportBeans = new ArrayList<ExportBean>();
ExportBean exportBean = new ExportBean();
exportBean.setBooleanValue(true);
exportBean.setKeyValue("PRE_APPROVED_OFFER");
exportBean.setStringValue("111");
exportBeans.add(exportBean);
exportBean.setBooleanValue(true);
exportBean.setKeyValue("PRE_APPROVED_OFFER1");
exportBean.setStringValue("222");
exportBeans.add(exportBean);
getLopRefNo(exportBeans);

When I iterate it

def getLopRefNo = {
    exportBeans->
       println "in function ${exportBeans}"
}

It shows only

in function [ExportMessagingBean{stringValue='222', keyValue='PRE_APPROVED_OFFER1', exportBoolean=true}, ExportMessagingBean{stringValue='222', keyValue='PRE_APPROVED_OFFER1', exportBoolean=true}]

It doesn't show the first record added. Is it missing anything?


Solution

  • The problem has nothing to do with Groovy. In your code, you are not actually adding two objects, you are adding one object and modifying it.

    List<ExportBean> exportBeans = new ArrayList<ExportBean>();
    ExportBean exportBean = new ExportBean();
    exportBean.setBooleanValue(true);
    exportBean.setKeyValue("PRE_APPROVED_OFFER");
    exportBean.setStringValue("111");
    
    exportBeans.add(exportBean); // add object to list
    
    exportBean.setBooleanValue(true);
    exportBean.setKeyValue("PRE_APPROVED_OFFER1");
    exportBean.setStringValue("222");
    
    exportBeans.add(exportBean); // this time, the same reference is "added". This does not result in an addition (in fact, "add" will return false here
    
    getLopRefNo(exportBeans);
    

    You are calling add with an object that is already present in the list so it has no effect. What you should do is create another instance of ExportBean, like this:

    List<ExportBean> exportBeans = new ArrayList<ExportBean>();
    ExportBean exportBean = new ExportBean();
    exportBean.setBooleanValue(true);
    exportBean.setKeyValue("PRE_APPROVED_OFFER");
    exportBean.setStringValue("111");
    
    exportBeans.add(exportBean); // add object to list
    
    exportBean = new ExportBean(); //create new instance of ExportBean
    exportBean.setBooleanValue(true);
    exportBean.setKeyValue("PRE_APPROVED_OFFER1");
    exportBean.setStringValue("222");
    
    exportBeans.add(exportBean); // this new instance will be correctly added
    
    getLopRefNo(exportBeans);