Finding the Max/Min Value in an Array of Primitives Using Java

Finding the max/min value in an array of primitives using Java

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.

how to get the minimum,maximum value of an array?

int[] convertedValues = new int[10];
int max = convertedValues[0];

for (int i = 1; i < convertedValues.length; i++) {
if (convertedValues[i] > max) {
max = convertedValues[i];
}
}

Similarly find for the minimum value by changing lesser symbol.

Find the minimum and maximum number in an Array in Java

This has been solved here: Finding the max/min value in an array of primitives using Java

Don't forget to print outside the loop (to get one answer).

Random array with size, min and max value with short

I would do it like this.

  • first, method names by convention should start with lower case letters.
  • Use the method to generate the values and return the list
  • return interface types as opposed to implementation types (e.g. List)
  • throw exceptions if the arguments don't satisfy the requirements.

Note, having to cast the arguments to shorts is cumbersome but it prevents errors at compile time. Otherwise you may want to throw an additional run time exception if the values aren't within Short.MIN_VALUE and Short.MAX_VALUE.

public class RandomShorts {

public static void main(String[] args) {
List<Short> shortList = randomList(20, (short)200, (short)99);
shortList.forEach(System.out::println);
}

public static List<Short> randomList(short n, short maxVal,
short minVal) {

if (n <= 0 || minVal >= maxVal) {
throw new IllegalArgumentException(
"\nn must be > 0\nminVal must be < maxVal\n");
}

List<Short> ran = new ArrayList<>();

Random rand = new Random();
for (int i = 0; i < n; i++) {
short result =
(short) (rand.nextInt(maxVal - minVal) + minVal);
ran.add(result);
}
return ran;
}
}

If you just want to return a single random number using the supplied arguments, they you can do it like this.

public static short randomShort(int n, short maxVal, short minVal) {
return (short)((Math.random()*(maxVal - minVal))+minVal);
}

Using java write two methods min and max to find maximum value and minimum value in linked list but the input list is array of integers

Code you given is executing in correct manner.

You can also use

MaximumMinimum sList = new MaximumMinimum(); 
List<Integer> list = new ArrayList<>();
Node head = sList.head;
while(head != null){
list.add(head.data);
head= head.next;
}
//no recommended if you want to design your own method
System.out.println(list);
System.out.println(Collections.max(list));
System.out.println(Collections.min(list));

For inputting array of integers to

public void stores(int[] array)
{
for(int element:array)
{
this.addNode(element);
}
}

then if you run in main

 int[] elements = {1, 78, -9, 42 , 0, 14};
sList.stores(elements);
sList.maxNode(); //78
sList.minNode();//-9

Also you can use Arrays.stream(array_name).forEach(e->sList.add(e)) if You want to do it in java 8 way.

Min value array of int with streams

You're over-complicating it.

IntStream.of(args).min().getAsInt()

Note: this will throw a NoSuchElementException if the array is empty, which is probably a desirable result.

find min max in an array of integer, performance issue

Ok, following advices from the comments I think I did a better benchmark.
What I used is Java Microbenchmark Harness. I never used it before so I based my test on this handy tutorial.

What I did was creating a JMH test like follows:

public class MinMaxBenchmark {

@State(Scope.Benchmark)
public static class MyState {

int arraySize = 50_0000;
int[] elements = new int[arraySize];

@Setup(Level.Trial)
public void doSetup() {
List<Integer> list = new ArrayList<>(arraySize);
for (int k = 0; k < arraySize; k++) {
list.add(k);
}
Collections.sort(list);
Integer[] integers = list.toArray(new Integer[0]);
for (int k = 0; k < arraySize; k++) {
elements[k] = integers[k];
}

}
}


@Benchmark @BenchmarkMode(Mode.SampleTime ) @OutputTimeUnit(TimeUnit.MILLISECONDS)
public Pair classic(MyState state) {
return classicMinMax(state.elements);
}
@Benchmark @BenchmarkMode(Mode.SampleTime) @OutputTimeUnit(TimeUnit.MILLISECONDS)
public Pair divide(MyState state) {
return divideAndConquer(state.elements);
}

}

I put special attention to create the array (input data) outside the benchmark creating a @State with a @Setup method for initialization. Than I wrote the to @Benchmark methos. I was really careful in returning the result so dead code could be avoided (it's all in the tutorial).

With this setup I run several trials. This one is the last attempt:


Benchmark Mode Cnt Score Error Units
MinMaxBenchmark.classic sample 994028 0.202 ± 0.001 ms/op
MinMaxBenchmark.classic:classic·p0.00 sample 0.153 ms/op
MinMaxBenchmark.classic:classic·p0.50 sample 0.180 ms/op
MinMaxBenchmark.classic:classic·p0.90 sample 0.259 ms/op
MinMaxBenchmark.classic:classic·p0.95 sample 0.311 ms/op
MinMaxBenchmark.classic:classic·p0.99 sample 0.409 ms/op
MinMaxBenchmark.classic:classic·p0.999 sample 0.567 ms/op
MinMaxBenchmark.classic:classic·p0.9999 sample 0.942 ms/op
MinMaxBenchmark.classic:classic·p1.00 sample 2.617 ms/op
MinMaxBenchmark.divide sample 1226029 0.164 ± 0.001 ms/op
MinMaxBenchmark.divide:divide·p0.00 sample 0.126 ms/op
MinMaxBenchmark.divide:divide·p0.50 sample 0.149 ms/op
MinMaxBenchmark.divide:divide·p0.90 sample 0.201 ms/op
MinMaxBenchmark.divide:divide·p0.95 sample 0.230 ms/op
MinMaxBenchmark.divide:divide·p0.99 sample 0.327 ms/op
MinMaxBenchmark.divide:divide·p0.999 sample 0.522 ms/op
MinMaxBenchmark.divide:divide·p0.9999 sample 0.945 ms/op
MinMaxBenchmark.divide:divide·p1.00 sample 3.199 ms/op

Where actually the divide is only losing on p1.00 (I need to find the meaning).

So I guess it was a problem of the way I handled benchmarking.

Thank you for the help in the comments, especially @alfasin.

how to get min and max value from Array of Model class excluding zero

I would remove the invalid data before computing your aggregates:

ArrayList<VitalReportsDetails> details = new ArrayList<>();
for(VitalReportsDetails detail : hm.get("Weight")) {
if(!detail.getValue().equals("0")) { details.add(detail); }
}

int min, max;
if(details.isEmpty()) {
// No data => default values
min = 0;
max = 0;
} else {
min = Integer.parseInt(Collections.min(details, new VitalCompare()).getValue());
max = Integer.parseInt(Collections.max(details, new VitalCompare()).getValue());
}

You can probably also make "value" an int directly when parsing your JSON to avoid all the String-to-int conversions.

Finding the minimum value of int numbers in an array (Java)

There's no need for the outer loop, it only runs once and you don't use i anyway. why do you have it?

For the inner loop, you need to compare against the minimum value. Right now you are comparing it against the first element in the array, which is not necessarily the minimum value.

min = arr[0];
for (j=0; j < arr.length; j++) {
if (arr[j] < min) { //<---fix is here
min = arr[j];
}
}

Also you could start the loop at 1, since you don't need to compare arr[0] against itself (it was just assigned to min)

Java: Finding the highest value in an array

It's printing out a number every time it finds one that is higher than the current max (which happens to occur three times in your case.) Move the print outside of the for loop and you should be good.

for (int counter = 1; counter < decMax.length; counter++)
{
if (decMax[counter] > max)
{
max = decMax[counter];
}
}

System.out.println("The highest maximum for the December is: " + max);


Related Topics



Leave a reply



Submit