简体   繁体   中英

How to compare each record with all other records in a same List Java?

I have a list :

List<BookDTO> bookList = libraryDTO.getBooks();

int bookCounter = 0;
for (BookDTO bookdto : bookList)
{
       if ((!errors.isEmpty() && !errors.containsKey("book[" + bookCounter + "].bookRefNo") || errors.isEmpty()) &&
           // do comparison for each record with other records in same list ) {

           errors.put("book[" + bookCounter + "].bookRefNo", messageSource.getMessage("bookRefNo.cannot.be.same", null, null));
        }

    bookCounter++;
    }

Now, I dont know how to do the comparison checking.. basically if there are matching records(records that having same value), I should get the key.

I don't understand if having two books with same values should raise an error (it seems so looking at your code) or if you want just to skip it while counting.

In any case you can't do it with a data structure that doesn't take into account a key without looping the whole collection for every element (that is O(n^2) complexity).

Could you use something more suitable like a set?

List<BookDTO> bookList = libraryDTO.getBooks();
Set<BookDTO> bookSet = new HashSet<BookDTO>(bookList);

bookCounter = bookSet.size();

Of course this assumes that BookDTO has correct implementation for equals(..) and hashCode() . You can even use a sorted set like TreeSet<BookDTO> but this would assume that BookDTO implements Comparable<BookDTO> .

Ok I guess your BookDTO has a bookRefNo property and you don't want to have more than one book with the same bookRefNo.

One solution is to rely on the fact that a Set contains no duplicate elements, so in your loop you could do something like this:

Set<String> bookRefs = new HashSet<String>();
for (BookDTO bookdto : bookList)
{
    if (!bookRefs.add(bookDto.getBookRef()))
    {
        // if we are here we tried to insert the same bookRef more than once...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM