int array[] = new int[]{10, 11, 88, 2, 12, 9};
public static int getMax(int[] inputArray){
int maxValue = inputArray[0];
for(int i=1;i < inputArray.length;i++){
if(inputArray[i] > maxValue){
maxValue = inputArray[i];
}
}
return maxValue;
}
Is there any way to find the maximum value but lower than 88 in the array?
If you use Integers you can do it using a TreeSet
Integer[] values = new Integer[]{10, 11, 88, 2, 12, 9};
NavigableSet<Integer> integers = new TreeSet<>(Arrays.asList(values));
System.out.println(integers.lower(88));
System.out.println(integers.lower(2));
System.out.println(integers.lower(100));
prints out
12
null
88
The javadoc of NavigableSet.lower(E e) says:
Returns the greatest element in this set strictly less than the given element, or null if there is no such element.
If you use Java8, you can use the Streaming API:
int[] array = new int[]{10, 11, 88, 2, 12, 9};
final int limit = 88;
Optional<Integer> max = Arrays.stream(array).filter(i -> i < limit)
.boxed().max(Comparator.naturalOrder());
System.out.println("Biggest element smaller than " + limit + " is " + max.get());
Output:
Biggest element smaller than 88 is 12
It does the following:
int array to a stream.filter)Integer stream (.boxed).max)The key part of the stream is the filter where the elements that are greater than the limit are removed from the stream.
UPDATE: If the index is also needed
List<Integer> intList = Arrays.asList(0, 11, 88, 2, 12, 9);
final int limit = 88;
IntStream.range(0, intList.size())
.filter(i -> intList.get(i) < limit)
.boxed().max(Comparator.comparing(intList::get))
.ifPresent(resultIndex -> System.out.println("Index " + resultIndex + ", value " + intList.get(resultIndex)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With