How to get elements of an array that is not null

后端 未结 2 962
我寻月下人不归
我寻月下人不归 2021-01-29 00:19

I am doing gift (String-type) storage, using arrays, with the maximum 500 million. I want to get the number of used elements in an array like how many gifts are currently in sto

2条回答
  •  梦谈多话
    2021-01-29 01:05

    You can use Arrays.stream to iterate over this array of strings, then use filter to select nonNull elements and count them:

    String[] arr = {"aaa", null, "bbb", null, "ccc", null};
    
    long count = Arrays.stream(arr).filter(Objects::nonNull).count();
    
    System.out.println(count); // 3
    

    Or if you want to find the index of the first null element to insert some value there:

    int index = IntStream.range(0, arr.length)
            .filter(i -> arr[i] == null)
            .findFirst()
            .getAsInt();
    
    arr[index] = "ffffd";
    
    System.out.println(index); // 1
    System.out.println(Arrays.toString(arr));
    // [aaa, ffffd, bbb, null, ccc, null]
    

    See also: How to find duplicate elements in array in effective way?

提交回复
热议问题