phil phil - 6 months ago 22
Java Question

Arraylist of Arrays with Java Stream

i got a method which returns a ArrayList with Arrays, like this inside:

{1,2,3}, {4,5,6}, {7,8,9}....

public int[] simulatePlays(BitBoard board, int number){
int[] count = {0,0,0};

while (number > 0){
BitBoard b = new BitBoard(board);
count[playRandomly(b)+1] += 1;
number--;
}
return count;
}

public ArrayList<int[]> evaluateMoves(BitBoard board, int number){
ArrayList<Integer> moves = board.listMoves();
ArrayList<int[]> values = new ArrayList<>();

for(int move : moves){
board.makeMove(move);
values.add(simulatePlays(board, number));
board.undoMove();
}
return values;
}


Now i need to multiple the value of array[3]


i mean as shown aboth value 3,6,9 the third value of every array.


with something and then pick the index of the max value. I could do it with two for loops but i would rather use Streams.

The Python code which doese what i want is:

values = [r* board.turn for l,m,r in evaluate_moves(board)]
max_val = max(values)
max_idx = values.index(max_val)


Can somebody help me ?

Answer

Due to nature of java streams it is not possible to retrieve element index from source. For example, you could use parallelStream() instead of stream and due to source would be splitted by Spliterator it still should work perfect.

To get information about only max multiple of 3rd element with some value you could use logic like that:

List<int[]> moves = new ArrayList<>();
moves.add(new int[]{1, 2, 3});
moves.add(new int[]{4, 5, 6});
moves.add(new int[]{7, 8, 9});

int someValue = 1;
Integer maxValue = moves.stream().map(array -> array[2] * someValue).reduce(0, Integer::max);
System.out.println(maxValue);

Update If you want to also have index, it is more appropriate to use 2 loops.

int maxValue = Integer.MIN_VALUE;
int indexMaxValueArray = 0;

for (int i = 0; i < moves.size(); i++) {
    if (someValue * moves.get(i)[2] > maxValue) {
        maxValue = someValue * moves.get(i)[2];
        indexMaxValueArray = i;
    }
}
System.out.println("maxValue = " + maxValue);
System.out.println("index of array in list = " + indexMaxValueArray);