java—如何获取非空数组的元素

pcww981p  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(582)

我在做礼品(字符串类型)存储,使用数组,最多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++;
    }
}
35g0bw71

35g0bw711#

您可以遍历数组并对初始化的数组元素进行计数。

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

而且如果你用它会更好 ArrayList<String> 所以你可以用 size() ```
ArrayList arrayName = new ArrayList(20);
System.out.println(arrayName.size());

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

baubqpgj2#

你可以用 Arrays.stream 若要迭代此字符串数组,请使用 filter 选择 nonNull 元素和 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]

另请参阅:如何有效地查找数组中的重复元素?

相关问题