简体   繁体   中英

Finding max record with java

I have a problem statement and would like to know the best way of solving that in java.

I have large number of records(1 million say) the records have timestamp and a value. I have to get output like in a span of each 15 min which is the highest value.

E.g.
Timestamp
-07-10-2013 10.15 - 14
-07-10-2013 10.18 - 13
-07-10-2013 10.19 - 18
-07-10-2013 10.30 - 16
-07-10-2013 10.34 - 10
-07-10-2013 10.38 - 17
-07-10-2013 10.42 - 30
-07-10-2013 10.54 - 23
-07-10-2013 10.57 - 44

Output

-07-10-2013 10.19 - 18
-07-10-2013 10.42 - 30
-07-10-2013 10.57 - 44

What is the best way of doing it in java. Iterating through each record looks a tedious thing. Any help will be great.

You can't get the max value without iteration through each value, unless they have some kind of predefined order, which you can use for optimization.

I would use Map to accumulate highest value, comparing it to previously stored, that way you can get the highest value in one iteration through the records.

Make a Comparator for your class. Store your objects in a TreeSet. Use TreeSet.descendingIterator to to show n objects with highest timestamps.

Note that this solution is good only if the timestamps are guaranteed to be unique. Otherwise use PriorityQueue.

Write a Comparator and use

Collections.sort(list, Collections.reverseOrder(yourComparator));

and get the first element from your list always.

i would suggest TreeSet , tree set is sortable and navigable its what you need. do not forget using comparator it provide compare function which is used for identifying min,max,sorting.

It is not necessary to sort the entire list if you want only the maximum value. Instead you can use Bubble Sort and in one iteration, you would get the highest value(complexity is O(n)). Note that TreeSet and Collections.sort are quite expensive as they try to sort the entire collection which is not required in your case.

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