有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在ArrayList中比较运行时上一个索引和当前索引

我正在检查以前的ArrayList索引的值是否与当前索引的值相同的运行时。如果前一个值与当前值相同,则我不想再次添加到列表中。我该怎么做?请在下面找到我一直在尝试的代码:

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);
        }
    }                       
}

共 (1) 个答案

  1. # 1 楼答案

    我认为你不需要在里面使用迭代器。只需使用size()方法获取最后一个索引

    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);
        }
    }
    

    注意:您可以在对象的equals()方法中使用带有相等逻辑的HashSet,而不是使用ArrayList