How to find the most significant number of negative integers in java? I have the following code and work well with positive integers. This is the code:
int max = 0; // not initialsing it also makes it 0
int[] n = {-1,-2,-3,-4};
for(int i = 0; i < n.lenght; i )
if(max < n[i])
max = n[i];
Now, I can solve it by reducing the max
variable to -5
or something below -4
, but this is inefficient because we don't know the lowest value.
So, how can it be achieved?
CodePudding user response:
If i understood your question correctly, you are looking for the highest
integer value within a list of integers.
You may use IntStream
s to get the highest value of your data.
IntStream stream = IntStream.of(-9, -18, 54, 8, 7, 14, 3);
OptionalInt obj = stream.max(); // or use stream.min() for the lowest integer
if (obj.isPresent()) {
System.out.println(obj.getAsInt()); // 54
}
else {
System.out.println("stream is empty");
}
As @OneCricketeer suggested, can also use your existing int[]
with streams:
int[] n = {-1, -2, -3, -4}; // your array of data
IntStream stream = Arrays.stream(n);
OptionalInt obj = stream.max();
if (obj.isPresent()) {
System.out.println(obj.getAsInt()); // -1
} else {
System.out.println("stream is empty");
}
CodePudding user response:
- The return type of your methode has to be the int wrapper class Integer, because you accept any values in the int array so the only way to show the user that the array doesn't have an max, which only could happen if the array is empty, is to return null.
- Now because your secure the case that the array could be empty the only other case is that the array has at least one element or more now you can initialize your start variable like this
max = n[0]
because if your array has only one element it has to be the greatest. For the other cases your loop will do the rest.
So there are two solutions first iterate by your own
private static Integer max(int[] numbers) {
if (numbers.length != 0) {
int max = numbers[0];
for (int i = 1; i < numbers.length; i )
if (max < numbers[i]){
max = numbers[i];
}
return max;
}
return null;
}
or second use only the API methodes (could be expansive)
private static Integer max(int[] numbers) {
OptionalInt result = Arrays.stream(numbers).max();
return result.isPresent() ? result.getAsInt() : null;
}