1

I have two lists, as listA and listB. listA is a list of objects and listB is a list of Double values. I want to sort listA based on the values of listB. So basically, the output is a sorted listA which uses listB values for sorting. for example:

  listA = ["obj0", "obj1", "obj2", "obj3", "obj4"]
  listB = [0.012, 0.013, 0.010, 0.009, 0.015]

output should be:

  listA = ["obj3", "obj2", "obj0", "obj1", "obj4"]

My current solution is to create a new list based on the value & index pair of listB and then sort them based on the value and after that use this sorted list of pairs and create the sorted listA based on the original indices. I am trying to find an optimized way of doing it for example using the Comparator ... something like

  listA.sort(Comparator.comparingDouble(listB::indexOf));

but this is sorting based on the index of listB which basically doesn't sort it and returns the same order of listA. I want the Comparator use the value of listB while it considers each value belongs to a specific index.

P.S. Responses provided here assume LitsB is already sorted, which isn't the case here

Alan
  • 417
  • 1
  • 7
  • 22
  • I already saw this post. It was helpful but it's not exactly what i am looking for, since as i posted the solution when uses the Comparator assumes listB is already sorted. – Alan May 16 '22 at 20:43
  • I think creating a list of pairs (i.e. zipping the lists), sorting, then mapping to the first element of the pair sounds like a good (and understandable) solution. – knittl May 16 '22 at 20:55
  • I think there should be a solution using the Comparator which doesn't assume listB is already sorted like what is provided in the link you shared – Alan May 16 '22 at 20:58
  • Maybe `listA.sort(Comparator.comparingDouble(listB::get))` ? Just a blind guess – gui3 May 16 '22 at 20:59
  • 1
    `listA = IntStream.range(0, listA.size()).boxed().sorted(Comparator.comparingDouble(listB::get)).map(listA::get).collect(Collectors.toList());` – shmosel May 16 '22 at 21:32

0 Answers0