简体   繁体   中英

Java Sorting Data Structure

I am taking in a object with multiple data fields (3 string fields, two int fields) from a text file, calculating a certain numerical value, and then I need to place them in a data structure, one-by-one as I read them in from the file. By the end of parsing/calculating/storing, I need the structure to be sorted by that calculated value so I can continually retrieve/pop of the highest valued.

I'm thinking PriorityQueue, but are there any better structures for this?

EDIT: What would be faster? Having a structure that maintains itself to be sorted throughout the duration of the program flow OR just placing them in a list and sorting at the end?

I would use PriorityQueue, as you suggest. It uses a heap as the data structure which keeps the elements sorted as you go. Once you have finished, you essentially have an ordered list so you can efficiently read the elements off in order.

If you are looking for natural ordering you could choose TreeSet . where elements are ordered using their natural ordering , or by a Comparator provided at set creation time.

PriorityQueue is more apt if you have the numerical value calculated and stored as a variable inside the element object. In that case you may need to specify the appropriate Comparator For synchronized access, go for PriorityBlockingQueue

If I understand you correctly you read and calculate the value, put it in the Queue and only then you need the queue to be sorted? Because if you sort your queue only once (after reading all the data from the file) then you might want to use LinkedList , which implements Queue.

  • (i) Read your data and create the objects (they should implement CompareTo )
  • (ii) put all the objects in your LinkedList with linkedList.add(myObject)
  • (iii) sort the linked list Collections.sort(linkedList)
  • (iv) peek or pop the first element

If each one is an object, can you not just create a method compateTo which compares two of your objects to decide which should be first, and use that to sort your objects (Probably stored in an array or list?).

I think you should maybe look into this: Compare To

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