简体   繁体   中英

how to find the index of the maximum element of an integer array with null elements in it?

I have an ArrayList say:

List<Integer> intlist= Arrays.asList(11,34,500,null,81, null);

I want to get the index of the maximum. But I have null elements in it. How?

You can use a Stream to filter out the null values, and find the max value. If a max is found, you can use the indexOf method to find the index of this item in your list.

Code

List<Integer> intlist = Arrays.asList(11, 34, 500, null, 81, null);

int maxindex = intlist.stream()
            .filter(Objects::nonNull)
            .max(Integer::compare)
            .map(intlist::indexOf)
            .orElse(-1);

System.out.println(maxindex);

Result :

2

Alternative without finding the max + using index of

It's also possible to avoid the use of indexOf and directly get the max index by using a reduce method to compare all elements and keep the largest one. Here we create a stream to generate all possible indexes, and use those to check if the value is not null. After this check we reduce the stream to only preserve the index of the max value

int maxindex = IntStream.range(0, intlist.size())
            .filter(i -> intlist.get(i) != null)
            .reduce((i, j) -> intlist.get(i) > intlist.get(j) ? i : j)
            .orElse(-1);

System.out.println(maxindex);

You can use the Stream API to find the maximum value which you can pass to List#indexOf to get its index. Make sure to pass Objects::nonNull to Stream#filter to discard null elements.

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class Main {
    public static void main(String[] args) {
        List<Integer> intList = Arrays.asList(11, 34, 500, null, 81, null);
        int idxMax = intList.indexOf(intList.stream()
                                            .filter(Objects::nonNull)
                                            .max(Integer::compare)
                                            .orElse(-1) // You can put here any value just to avoid NoSuchElementException 
                                                        // in case intList is empty. For empty intList, intlist.indexOf(that_value)
                                                        // will return -1 because that_value doesn't exist in the empty intList
                                    );
        System.out.println(idxMax);
    }
}

Output:

2

Alternatively,

List<Integer> intList = Arrays.asList(11, 34, 500, null, 81, null);
int idxMax = intList.indexOf(intList.stream()
                                    .filter(Objects::nonNull)
                                    .reduce(Integer::max)
                                    .orElse(-1)
                            );
System.out.println(idxMax);

You can check for null elements to ignore them in the loop:

public static void main(String[] args) {
    System.out.println(getIndexOfMax(Arrays.asList(11,34,500,null,81, null))); //2
    System.out.println(getIndexOfMax(Arrays.asList(null,null,null,200))); //3
    System.out.println(getIndexOfMax(Arrays.asList(null,null,null))); //-1
}
private static int getIndexOfMax(List<Integer> list) {
    int indexOfMax = -1;
    int max = Integer.MIN_VALUE;
    for(int i = 0; i < list.size(); i++) {
        Integer num = list.get(i);
        if(num != null && num > max) {
            indexOfMax = i;
            max = num;
        }
    }
    return indexOfMax;
}

Sorry, I had misread the question. I would recommend creating a method and returning -1 if no max was found.


List<Integer> intlist= Arrays.asList(11,34,500,null,81, null);
int index = getIndexForMax(intlist);
if (index >= 0) {
     System.out.println(intlist.get(index));
}

prints

500

The method.

public static int getIndexForMax(List<Integer> list) {
   int indx = -1; // default index
   int max = Integer.MIN_VALUE; // smallest possible value
   for (int i = 0; i < list.size(); i++) {
      if (list.get(i) != null) {
        int cv = list.get(i); 
          if (cv > max) {
            max = cv;  // save max
            indx = i; // and its index
          }
      }
   }
   return indx;
}
    

try below code

public static Integer max(List<Integer> intList) {
    if (intList == null || intList.isEmpty()) {
        throw new IllegalArgumentException("Number list must not empty !");
    }
    Integer max = intList.get(0);
    for (int i = 1; i < intList.size(); i++) {
        if (max != null && intList.get(i) != null && max < intList.get(i)) {
            max = intList.get(i);
        }
    }
    return max;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM