java 像 array.length 这样不包含 NULL 元素的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7466102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:05:56  来源:igfitidea点击:

Function like array.length that doesn't include NULL elements?

javaarraysnull

提问by Wex

TreeNode[] children = grid[row][col].getChildren();

I would like a simple function that can tell me how many objects are in this array? getChildren()will return an object of size no larger than 4, for example:

我想要一个简单的函数来告诉我这个数组中有多少个对象?getChildren()将返回大小不超过 4 的对象,例如:

children[0] = null;
children[1] = TreeNode Object
children[2] = null;
children[3] = null;

回答by Petar Ivanov

Why don't you write it yourself:

为什么不自己写:

public static <T> int getLength(T[] arr){
    int count = 0;
    for(T el : arr)
        if (el != null)
            ++count;
    return count;
}

回答by JRL

Other alternative:

其他选择:

ArrayList l = new ArrayList(Arrays.asList(children));
l.removeAll(Collections.singleton(null)); 
l.size();

回答by Michael Brewer-Davis

Perhaps overkill to use predicates, but here's a Guava solution:

使用谓词可能有点矫枉过正,但这里有一个番石榴解决方案:

int numNotNull = Iterables.size( Iterables.filter( Arrays.asList( children ),
                        Predicates.notNull() ));

回答by mumrah

In Java 8, you can use Math.toIntExactand Arrays.streamto construct a nice one-liner:

在 Java 8 中,你可以使用Math.toIntExactArrays.stream来构造一个很好的单行:

Math.toIntExact(Arrays.stream(row).filter(s -> s != null).count())

回答by Kirill Terentyev

Code:

代码:

Arrays.stream(list).filter(e -> e != null).count();

回答by robertmoggach

This should work. Essentially the same with the function written for you and not TreeNode specific.

这应该有效。本质上与为您编写的函数相同,而不是特定于 TreeNode。

int initLength(Object[] myArray) {
  int count = 0;
  for (Object obj : myArray) {
    if ( obj != null ) count++;
  }
  return count;
}

I called it initLength because those items are init'd but call it what you like. Some would say it's init'd when you define it, regardless of whether the contents are null.

我将其称为 initLength 是因为这些项目已初始化但您可以随意称呼它。有人会说它在定义时已初始化,无论内容是否为空。