# [ACCEPTED]-How to find maximum value of set of variables-max

Score: 24

In Java, you can use Math.max like this:

``````double maxStock = Math.max( firstQuarter, Math.max( secondQuarter, Math.max( thirdQuarter, fourthQuarter ) ) );
``````

Not the 3 most elegant, but it will work.

Alternatively, for 2 a more robust solution define the following 1 function:

``````private double findMax(double... vals) {
double max = Double.NEGATIVE_INFINITY;

for (double d : vals) {
if (d > max) max = d;
}

return max;
}
``````

Which you can then call by:

``````double maxStock = findMax(firstQuarter, secondQuarter, thirdQuarter, fourthQuarter);
``````
Score: 4

One method to rule them all

``````public static <T extends Comparable<T>> T max(T...values) {
if (values.length <= 0)
throw new IllegalArgumentException();

T m = values[0];
for (int i = 1; i < values.length; ++i) {
if (values[i].compareTo(m) > 0)
m = values[i];
}

return m;
}
``````

0

Score: 2

With primitive variables the best choice 5 maybe with Arrays or Collections:

Arrays:

``````double [ ] data = { firstQuarter , secondQuarter , thirdQuarter , fourtQuarter ) ;
Arrays . sort ( data ) [ 3 ] ;
``````

Collections:

``````List<Double> data = new Arraylist<Double>();
Collections.sort(data);
data.get(3);
``````

And 4 if you work with Objects you may use Collections 3 with a Comparator:

``````class Quarter {
private double value;
private int order;

// gets and sets
}
``````

And to get the max value:

``````List<Quarter> list = new ArrayList<Quarter>();
Quarter fisrt = new Quarter();
first.setValue(firstQuarter);
first.setOrder(1);
// Do the same with the other values
Collections.sort(list, new Comparator<Quarter>(){
compare(Object o1, Object o2){
return Double.valueOf(o1.getValue()).compareTo(o2.getValue());
}
}
``````

This 2 may be more complex, but if you working 1 with objects i think is better to work.

Score: 2

I believe now in Java 8 the most concise 1 version would look like this:

``````DoubleStream.of(firstQuarter , secondQuarter , thirdQuarter , fourtQuarter).max();
``````
Score: 1
``````double [ ] data = { firstQuarter , secondQuarter , thirdQuarter , fourtQuarter ) ;
Arrays . sort ( data ) [ 3 ] ;
``````

0

Score: 1

A little late to the party, but for anyone 9 else viewing this question, java 8 has primitive 8 stream types that implement exactly this

``````Collection<Integer> values = new ArrayList<>();
OptionalInt max = values.stream().mapToInt((x) -> x).max();
``````

`mapToInt` 7 is the key function that describes how to 6 convert the input to an integer type. The 5 resulting stream then has additional aggregators 4 and collectors specific to integer types, one 3 of the being `max()`.

The result value can then 2 be extracted from the `OptionalInt`, if the operation 1 was successful

Score: 0
``````Max = firstQuarter;
If(secondQuarter > max)
Max = secondQuarter;
``````

... And so on

0

More Related questions