Jaykumar Jaykumar - 1 year ago 41
Java Question

Count elements of a list using While loop in java

I am passing some parameters in the URL and then I add them in a list. My list has a limit of 5 elements. So if someone adds 6th element in the URL the list would simply ignore it. So I am trying to use a counter but the logic is not working as desired. I am using

loop to achieve this. So if list size is smaller than 5 set the agencyCds otherwise just return the list.

private List<IUiIntegrationDto> generateViewIntegrationReportData(ESignatureIntegrationConfig eSignConfig) throws Exception {
int counter = 1;
if(eSignConfig.getAdditionalAgencyCds() != null ) {

List<String> combinedAgencyCds = new ArrayList<String>();

for(String agencyCd : eSignConfig.getAgencyCd()) {

StringTokenizer token = new StringTokenizer(eSignConfig.getAdditionalAgencyCds().toString(), StringConstants.COMMA);
while(token.hasMoreTokens()) {

while(combinedAgencyCds.size() < 5) {
counter = counter + 1;

// eSignConfig.setAgencyCd(combinedAgencyCds);
List<IUiIntegrationDto> intgList = getUiIntegrationManager().retrieveUiIntegrationReportData(eSignConfig.getAgencyCd(), eSignConfig.getCreatedDays(),
eSignConfig.getLob(), eSignConfig.getTransactionStatus(), eSignConfig.getAccounts(), eSignConfig.getSortKey(), eSignConfig.getSortOrder());

return intgList;

I am not completely sure about this logic if it is correct or if there is nay better approach.


Answer Source

Try this instead of the last while in your code:

if(combinedAgencyCds.size() <= 5) {
} else {
   eSignConfig.setAgencyCd(combinedAgencyCds.subList(0, 5));

The full combined list will then be used if it is less than 5 in size. Otherwise, only the first 5 elements are used.

Edit: Or even better:

eSignConfig.setAgencyCd(combinedAgencyCds.subList(0, Math.min(5, combinedAgencyCds.size())));