sorting - Sort Java List from closest to farthest (with multiple keys) -


i wish sort java list closest farthest relative particular value.

for example :

the list :

{4,5,8,4,5,1,2,10,1,0,12} 

for comparison oh value 3 becomes :

{4,4,5,5,2,1,1,0,8,10,12} 

thus, first values @ distance of 1 number 3 , @ distance of 2 of number 3 ...

i tried arraylist comparator, not see how compare 2 two. treemap distances keys need not unique.

i hope have been clear!

do have solution ? thank you

this how it

public class main {     public static void main(string[] args) {          list<integer> arr = arrays.aslist(4, 5, 8, 4, 5, 1, 2, 10, 1, 0, 12);         final int pivot = 3;          collections.sort(arr, new comparator<integer>() {             public int compare(integer a, integer b) {                 int d1 = math.abs(a - pivot);                 int d2 = math.abs(b - pivot);                 return integer.compare(d1, d2);             }         });          system.out.println(arr);     } } 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -