user3338991
user3338991

Reputation:

max value from arraylist part?

i have some int values stored in ArrayList1 (imagine a table with one column). I need to create another ArrayList2 (second column), which will have values, that are the max values of a range in ArrayList1, for example last 3 values. for example:

1 null
2 null
1 2
3 3
2 3
1 3

So the secondt column - ArrayList2, will contain for each row max value of the last 3 corresponding rows in ArrayList1. (same as in xls, B3=MAX(A1:A3)...). I can do it by creating for each row with a loop that goes and finds out max value, or i can loop and create subArrayList and use collections.max, but both these solutions require a loop for every row, which isn't very practical, isnt there a simpler way? something like arrayList.max(1,3) to get the number straight away?

Upvotes: 1

Views: 1314

Answers (3)

Mario Cervera
Mario Cervera

Reputation: 671

You can do something like the code I show below. You iterate the first array, calculating the maximum and updating the second array accordingly. Note that you need an extra array to store the intervals.

private void m1(List<Integer> array1, List<Integer> array2, int range) {

    Integer[] rangeArray = new Integer[range];

    //Iterate first array

    for(int i = 0; i < array1.size(); i++) {

        Integer x = array1.get(i);

        rangeArray[i%range] = x;

        //Update second array

        if(i < range - 1) {
            array2.add(null);
        }
        else {
            int max = Collections.max(Arrays.asList(rangeArray));
            array2.add(max);
        }
    }
}

Upvotes: 2

awsome
awsome

Reputation: 2153

Using Collections.max

    int startFrom = 2; // configurable number
    List<Integer> intList = Arrays.asList(1,2,1,3,2,1,4);
    List<Integer> sortedList =  new ArrayList<>();
    for (int i = 0; i < intList.size(); i++) {
        if(i < startFrom){
            sortedList.add(null);
            continue;
        }
        ArrayList<Integer> list = new ArrayList<Integer>(intList.subList(i -startFrom, i+1));
        sortedList.add(Collections.max(list));
    }
    System.out.println(sortedList);

Output is :[null, null, 2, 3, 3, 3, 4]

Upvotes: 1

SomeDude
SomeDude

Reputation: 14228

Ok. So your size of list to compare can vary , in that case build an array list out of the numbers to compare say List<?> list = Arrays.asList( numbersToCompare ); then Collections.max( list ), the list should contain objects that can be compared in other words needs to be comparable. ( If not write your own comparator )

Upvotes: 0

Related Questions