• Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Sally william
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys..

I have a list :




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.

please guide...
 
Campbell Ritchie
Marshal
Posts: 56527
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It all depends what sort of data structure you are using. A List usually does that by a linear search, but you might do well to combine that List with a Map or Set which can find its elements much more rapidly. A linear search runs in O(n) time but some classes, eg this one can provide contains() methods which run in O(1) time. Note those methods depend on the equals() and hashCode() methods being correctly overridden. If you use a hash‑based collection and the hash code changes, it will probably become impossible to retrieve the object from the collection.
you should look for search algorithms, linear and binary, as well as reading about hash codes.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sally william wrote: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.
please guide...

Well it seems to me you've gone about this bass ackwards. Don't start coding until you know what you want to do...and I'm still not quite sure what that is.

Are you saying that your booklist may contain duplicate BookDTO objects?
If so and, as Campbell said, that can be determined by its equals() method, AND that equals() method has a corresponding hashCode() method (and if it doesn't, shoot the developer), then I would suggest loading all the records in your List into a LinkedHashMap<BookDTO, List<Integer>>, where the key is the Book itself, and the List<Integer> is a list of all indexes in the list that contain that book.

Then you can go through all the keys in your Map, which will be distinct books.

Alternatively, if BookDTO is Comparable, or you can write a Comparator for it, you can sort your List.

HIH

Winston
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!