How to return the k-th element in TreeSet in Java?

后端 未结 8 2017
-上瘾入骨i
-上瘾入骨i 2020-12-30 01:07

Maybe I am not using the right data structure. I need to use a set, but also want to efficiently return the k-th smallest element. Can TreeSet in Java do this?

8条回答
  •  情深已故
    2020-12-30 01:24

    You just need to iterate to element k. One way to do that would be to use one of Guava's Iterables.get methods:

    T element = Iterables.get(set, k);
    

    There's no built in method to do this because a Set is not a List and index-based operations like that are generally the reserved for Lists. A TreeSet is more appropriate for things like finding the closest contained element that is >= some value.

    One thing you could do if the fastest possible access to the kth smallest element were really important would be to use an ArrayList rather than a TreeSet and handle inserts by binary searching for the insertion point and either inserting the element at that index or replacing the existing element at that index, depending on the result of the search. Then you could get the kth smallest element in O(1) by just calling get(k).

    You could even create an implementation of SortedSet that handles all that and adds the get(index) method if you really wanted.

提交回复
热议问题