Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find greater than X from list when X doesn't exist in list

I am trying to find values from a list that are greater than certain value (known in my case).

Example:

Given

list = [1, 2, 5, 10, 15];  //list is sorted

Find values greater than X (=7 in this case).

Desired result = Return a list with values = [10, 15]

I tried using java binary search, like

int index = Collections.binarySearch(list, X);

My plan was to find index (of X) and then return all the elements after index.

But index return negative, that I understand because 7 is not in the list.

Is there any other way ? Someone please suggest.

like image 429
Script_Junkie Avatar asked Oct 18 '25 13:10

Script_Junkie


2 Answers

If your list is sorted than Collection#binarySearch will return the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). You can calculate begin index of insertion_point like below:

     index= -(insertion_point) - 1
     -(insertion_point)= index+1
     insertion_point=-(index+1)

After got the begin index of List than you can apply subList method to got the resulted list greater than X.

    Integer[] values = {1, 2, 5, 10, 15};
    List<Integer> list = new ArrayList<>(Arrays.asList(values));
    int X = 7;
    int index = Collections.binarySearch(list, X);

    int insertion_point = -(index+1); // As calculated above.

    List<Integer> res = list.subList(insertion_point, list.size());
    System.out.println(res);

Output: [10, 15]

like image 85
Masudul Avatar answered Oct 21 '25 04:10

Masudul


Since Java 8, you can use streams.

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;

public class So1 {

   public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 5, 10, 15);
        List result = list.stream().filter(s -> s > 7).collect(Collectors.toList());
        System.out.println(result);
    }
}

For those kind of data computations, I seriously recommand looking into Clojure, which compiles to Java.

For example, this is how you would write it:

(filter
    #(> % 7) 
    [1 2 5 10 15])
like image 40
Nicolas Modrzyk Avatar answered Oct 21 '25 04:10

Nicolas Modrzyk