This is basically to avoid redundant code. I have two different arrays, one of Float type and one Integer type. I need to find index of maximum element in both the arrays which is easy to do as I can write two different methods, one for comparing float and one for comparing Integers.
What am trying to do improve is to write just one common method which can take in either of the array as argument and can return me the max index. What I have tried unsuccessfully so far is:
private static int findMaxIndex(Object [] arr){
int maxIndex =(int) IntStream.range(0,arr.length)
.boxed()
.max(Comparator.comparingInt(i -> arr[i])) // getting compiler error here
.map(max->arr[max])
.orElse(-1);
return maxIndex;
}
and am looking to call this method like this:
Float [] a = {0.3f, 0.5f, 0.9f, 0.7f, 0.1f};
Integer []b = {3000, 250, 100, 2000, 2000, 10246};
int maxIndexFloatArray = findMaxIndex(a);
int maxIndexIntegerArray = findMaxIndex(b);
Am pretty sure there are easier ways to do this, but am a bit rusty now in hands on java code. Hope this explains the question correctly.