dbulgakov dbulgakov - 1 month ago 8
Java Question

Split ArrayList of integers using RxJava

I am trying to split an list of integers into smaller arrays (ranges) by values from another list. So, for instance, having an array with such values

[100, 10, 4000, 9, 3000, 1024, 15, 660, 999]


And array of values to split by.

[20, 300, 500, 1000, 10000]


I want to get arrays with values, that are less then corresponding values. Like

20 -- [9, 10, 15] // (value from first array < 20)
300 -- [100] // (20 <= value < 300)
500 -- [] // (300 <= value < 500)
1000 -- [660, 999] // (500 <= value < 1000)
10000 -- [1024, 3000, 4000] // (1000 <= value < 10000)


Is there any way to implement this using RxJava? Or any fast algorithm to do that?

Answer

This seems to work:

public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(100);
        list.add(10);
        list.add(4000);
        list.add(9);
        list.add(3000);
        list.add(1024);
        list.add(15);
        list.add(660);
        list.add(999);
        int[] splitValues = new int[]{20,300,500,1000,10000};
        int prev = 0;
        //100, 10, 4000, 9, 3000, 1024, 15, 660, 999
        Collections.sort(list);
        Map<Integer, Integer[]> map = new HashMap<Integer,Integer[]>();
        for (int i = 0; i < splitValues.length; i++) {
            for (int j=prev;j<list.size();j++) {
                if(splitValues[i]<list.get(j)){
                    addRecord(map,list,j, splitValues[i],prev);
                    prev = j;
                    break;
                }
            }
        }
        System.out.println(map);
    }

    private static void addRecord(Map<Integer, Integer[]> map, List<Integer> list, int j, int index, int start) {
        try {
            list = list.subList(start, j);          
        } catch (Exception e) {
            System.out.println("boo");
        }

        Integer[] arr = new Integer[j-start];
        list.toArray(arr);
        map.put(index, arr);

    }

The only problem is displaying it

Comments