Java collection – top and bottom n elements

I have a very unique requirement that my collection should contain only the top and bottom n elements These elements are comparable and the collection itself is bounded, which means that the evaluation is completed when an entry is added to the collection

For example, insert the following set of values into the top and bottom 10 collection

5,15,10,1,12,8,11,2,16,14,9,3,20,7

The collection should contain only the following

20,7,5,1

I am considering maintaining the sortedset of two N / 2 elements and merging them at the end, but this method is not clean and requires merging steps before using the results

I just hope someone can answer this question better

Solution

1. If you want sorting and uniqueness, please use Java util. TreeSet. In collection Your data will be sorted automatically in natural order and remain unique

2. Use collections Reverse() reverses the collection as needed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>