Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

It's trivial to write a function to determine the min/max value in an array, such as:

/**

 * 

 * @param chars

 * @return the max value in the array of chars

 */

private static int maxValue(char[] chars) {

    int max = chars[0];

    for (int ktr = 0; ktr < chars.length; ktr++) {

        if (chars[ktr] > max) {

            max = chars[ktr];

        }

    }

    return max;

}

but isn't this already done somewhere?

1 Answer

0 votes
by (46k points)

Using Commons Lang (to convert) + Collections (to min/max)

import java.util.Arrays;

import java.util.Collections;

import org.apache.commons.lang.ArrayUtils;

public class MinMaxValue {

    public static void main(String[] args) {

        char[] a = {'3', '5', '1', '4', '2'};

        List b = Arrays.asList(ArrayUtils.toObject(a));

        System.out.println(Collections.min(b));

        System.out.println(Collections.max(b));

   }

}

Note that Arrays.asList() wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Mar 24, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Apr 16, 2021 in Java by sheela_singh (9.5k points)

Browse Categories

...