【问题标题】:How to get elements of an array that is not null如何获取不为空的数组元素
【发布时间】:2020-12-16 18:02:00
【问题描述】:

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

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++;
    }
}

【问题讨论】:

    标签: java arrays user-input


    【解决方案1】:

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

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

    如果你使用ArrayList&lt;String&gt; 会更好,这样你就可以使用size()

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

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

    【讨论】:

      【解决方案2】:

      您可以使用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]
      

      另见:How to find duplicate elements in array in effective way?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-21
        • 2019-11-17
        • 2016-06-30
        • 1970-01-01
        • 1970-01-01
        • 2019-12-17
        • 2011-12-02
        相关资源
        最近更新 更多