如何获取非空数组的元素

How to get elements of an array that is not null

我是做礼物(String类型)存储的,用数组,最大5亿。我想获取数组中已使用元素的数量,例如当前有多少礼物,(即我存储了 253538 件礼物,但我不知道。Java 中是否有命令可以知道数组中只有 253538 个槽包含一个元素)。但我不知道该怎么做。这是我要使用的代码片段:

static String[] Gifts = new String[500000000];
static int i = 0;
String command, Gift;
while (true) {
    //Gift Array Console
    String command = scan.next();
    if (command == "addgift") {
        String Gift = scan.next();
        Gifts[i] = Gift;
        i++;
    }
}

您可以遍历数组并计算非空数组元素。

int counter = 0;
for (int i = 0; i < arrayName.length; i ++) {
    if (arrayName[i] != null)
        counter ++;
}

另外,如果你使用 ArrayList<String> 就更好了,这样你就可以使用 size()

List<String> arrayName = new ArrayList<String>(20);
System.out.println(arrayName.size());

它将打印 0,因为没有元素添加到 ArrayList。

您可以使用 Arrays.stream to iterate over this array of strings, then use filter to select nonNull elements and count 他们:

String[] arr = {"aaa", null, "bbb", null, "ccc", null};

long count = Arrays.stream(arr).filter(Objects::nonNull).count();

System.out.println(count); // 3

或者,如果您想找到第一个 null 元素的索引以在其中插入一些值:

int index = IntStream.range(0, arr.length)
        .filter(i -> arr[i] == null)
        .findFirst()
        .getAsInt();

arr[index] = "ddd";

System.out.println(index); // 1
System.out.println(Arrays.toString(arr));
// [aaa, ddd, bbb, null, ccc, null]

另请参阅:How to find duplicate elements in array in effective way?