Supposing I have this TreeSet<Integer>
:
1 3 4 6 8 9 10
And I want the top-k
"closest" elements to an input number x
.
For example, with k=3
and x=5
I want to get:
4 6 3
Is there any way to do this?
Supposing I have this TreeSet<Integer>
:
1 3 4 6 8 9 10
And I want the top-k
"closest" elements to an input number x
.
For example, with k=3
and x=5
I want to get:
4 6 3
Is there any way to do this?
It seems what you need to do is to get a headSet with all elements smaller than the target element and a tailSet for the bigger elements. Now the algorithm will be somewhat similar to merge phase of merge sort.
c_desc
, and c_asc
x
. Take this value and advance the iteratork
elementsBy "closest to x" I assume you mean the lowest values of abs(n - x)
.
That is, for x=5, k=3:
1,3,4,6,8,9,10 -> 3,4,6
3,4,5,10,11,12 -> 3,4,5
0,1,2,5,6,7,8 -> 5,6,7
If that's the case, I would:
Integer
to a Pair<Integer,Integer>
n -> new Pair(n, abs(n - x))
so one value is n
, the other is its distance from x
. Pair
, (ab)use Map.Entry
, (ab)use Integer[2]
or find one in a library)Pair<>
using a comparator that uses the distancek
elements from that sorted list.Using Java 8 streams:
set.stream()
.map( n -> new Pair(n, Math.abs(x - n)))
.sorted(Comparator.comparing( p -> p.right())
.limit(k)
.map( p -> p.left())
.collect(Collectors.toSet());