Sort Java collections with count based on count

We know that we can use

Collections.sort 

to sort the list after all inserted items.

But if the elements are inserted once, is SortedMap more efficient?

Although, SortedMap does not have a subList method.

I need something like SortedMap to effectively insert a small number of elements many times and can always get a 1 ~ 1000 substring from top to bottom with the Comparator interface.

Any suggestion?

+5
source share
1 answer

I think the SortedSet is a NavigableSet , which in turn has methods like subSet , tailSet , headSet , ceiling and floor for such problems.

So you can do something like:

 SortedSet<Integer> set = new TreeSet<>(Arrays.asList(0,1,2,3,4,5,6,7,8,9)); SortedSet<Integer> subset = set.subSet(3,7); System.out.println(subset); //[3,4,5,6] 

Obviously, you can create a TreeSet with any Comparator you want and search in the order that TreeSet you TreeSet .

 Comparator<Integer> reverse = Collections.reverseOrder(); SortedSet<Integer> set = new TreeSet<>(reverse); //same thing here 
+1
source

Source: https://habr.com/ru/post/1247841/


All Articles