Search code examples
javafor-looparraylistiteratorlistiterator

How to compare the previous index with current index on run time in ArrayList


I am checking on the run time that does previous index of ArrayList has the same values as current index has. If previous value is same as compare to the current value then I don't want to add again into the List. How can I do that? Please find below the code which I have been trying:

List<EventDto> liveEvents = new ArrayList<EventDto>();
EventDto liveTvEventDto = null;
List<CustomerEventDetails> customerDetails = odsRepository.getEventDetails(countryCode, customerId);        
if (customerDetails.size() > 0) {           
    for (CustomerEventDetails customerData : customerDetails) {
        liveTvEventDto = new EventDto();
        liveTvEventDto.setCountryCode(customerData.getCountryCode());
        liveTvEventDto.setCustomerId(customerData.getCustomerId());

        ListIterator<EventDto> listIterator =  liveEvents.listIterator();

        if (listIterator.previousIndex() == -1) {
            listIterator.next();    

            int i =listIterator.previousIndex();
            System.out.println("listIterator:"+liveEvents.get(i));
            if (!(StringUtility.trimmedOrEmptyIfNull(liveEvents.get(i).getCustomerId()).equals(StringUtility.trimmedOrEmptyIfNull(liveTvEventDto.getCustomerId()))
                                && StringUtility.trimmedOrEmptyIfNull(liveEvents.get(i).getCountryCode()).equals(StringUtility.trimmedOrEmptyIfNull(liveTvEventDto.getCountryCode()))))
                liveEvents.add(liveTvEventDto);
        }
    }                       
}

Solution

  • I don't think you need to use an iterator inside. Just get the last index using the size() method.

    for (CustomerEventDetails customerData : customerDetails) {
        liveTvEventDto = new EventDto();
        // Set member variables
    
        if (liveEvents.size() > 0) {
            System.out.println("Last Object: " + liveEvents.get(liveEvents.size() - 1));
    
            if (/* Logic for checking if the objects are NOT equal */)
                liveEvents.add(liveTvEventDto);
        } else {
            liveEvents.add(liveTvEventDto);
        }
    }
    

    Note: Instead of using ArrayList, you could use a HashSet with the logic for equality in the equals() method of the object.