[英]Java how to compare an element of an array with all the other elements of the same array
[英]How to compare each record with all other records in a same List Java?
我有一個清單:
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++;
}
現在,我不知道如何進行比較檢查..基本上如果有匹配的記錄(具有相同值的記錄),我應該得到密鑰。
我不明白是否有兩本具有相同值的書籍會引發錯誤(看起來如此看待你的代碼)或者你是否只想在計算時跳過它。
在任何情況下,如果沒有為每個元素循環整個集合(即O(n ^ 2)復雜度),則不能使用不考慮密鑰的數據結構。
你能用一套比較合適的東西嗎?
List<BookDTO> bookList = libraryDTO.getBooks();
Set<BookDTO> bookSet = new HashSet<BookDTO>(bookList);
bookCounter = bookSet.size();
當然,這假設BookDTO
具有equals(..)
和hashCode()
正確實現。 您甚至可以使用像TreeSet<BookDTO>
這樣的有序集,但這會假設BookDTO implements Comparable<BookDTO>
。
好吧,我猜你的BookDTO有一個bookRefNo屬性,你不希望有多本同一本書的書.RefNo。
一種解決方案是依賴於Set不包含重復元素的事實,因此在循環中你可以做這樣的事情:
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...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.