user10824969
user10824969

Reputation:

Creating an array of maximum values amongst rows of 2 dimensional array

I have created a 2 dimensional integer array for example

int[][] source = new int[][]{
        new int[]{1, 2, 3, 4},
        new int[]{-3, -7, -5, -5},
        new int[]{11, 3, 7, 9},
        new int[]{121, -41, 515, -466}
};

now I am creating an array of maximum value across the rows as :

int[] rowMax = new int[source.length];

for (int i = 0; i < source.length; i++) {
  int m = Integer.MIN_VALUE;
  for (int j = 0; j < source[0].length; j++) {
    if (source[i][j] > m) {
      m = source[i][j];
    }
  }
  rowMax[i] = m;
}

This works fine for me. Giving this a try with streams I could figure out that Finding the max/min value in an array of primitives using Java, in which case

int max = Arrays.stream(arr).max().getAsInt();

and I can update my inner loop as:

int[] rowMax = new int[source.length];
for (int i = 0; i < source.length; i++) {
  rowMax[i] = Arrays.stream(source[i]).max().getAsInt();
}

But I am not sure of how to do this for complete int[] rowMax if possible using streams further. Could this be converted at all?

Upvotes: 0

Views: 181

Answers (2)

Naman
Naman

Reputation: 31968

You can possibly try to update your iteration to iterate over Stream<int[]>

Arrays.stream(source) // convert to Stream<int[]>

then using your code map to maximum value per int[] using Stream.mapToInt as

mapToInt(ints -> Arrays.stream(ints).max().getAsInt())

and then collect them back to array using IntStream.toArray

toArray()

which would completely look like

int[] rowMax = Arrays.stream(source)
                     .mapToInt(ints -> Arrays.stream(ints).max().getAsInt())
                     .toArray();

IMHO, though this can also be represented as:

int[] rowMax = Stream.of(source) // Stream<int[]> for all rows
                     .mapToInt(ints ->
                             Stream.of(ints)  // Stream<int[]> for each row level
                                     .flatMapToInt(Arrays::stream) // IntStream
                                     .max().orElse(Integer.MIN_VALUE)) // return max per int[] with default value
                     .toArray(); // to array

Upvotes: 2

Ousmane D.
Ousmane D.

Reputation: 56453

You can do it as follows:

int[] maxNumbers = Arrays.stream(source) //Stream<int[]>
                         .mapToInt(a -> Arrays.stream(a).max().getAsInt()) // IntStream
                         .toArray();// int[]
  • create a stream from the two-dimensional array via Arrays.stream(source)
  • map each row (int[]) into the max value
  • collect the result to an array

Upvotes: 1

Related Questions