java生成一个方法,返回数组中的一位数 2 月 Questions & Answers 411 我正在尝试创建一个方法,该方法将查找数组中一位数的数量并返回值,例如,如果我的数组是[1,22,3,4,55,66,5],它将返回4,因为有4个一位数,并且是在java中
# 1 楼答案 因为我很无聊 public static int getOneDigitNumberCount(final int[] numbers) { if (numbers == null || numbers.length == 0) { return 0; } int count = 0; for (int number : numbers) { // assumes you're not considering negative numbers if (number >= 0 && number <= 9) { count++; } } return count; }
# 2 楼答案 另一个解决方案使用streams并考虑negative一位数 int[] nums = {1,22,3,4,-8, -9, -45, 55,66,5}; long count = Arrays.stream(nums) .filter(n -> n > -10 && n < 10) .count(); System.out.println(count); // prints 6
# 1 楼答案
因为我很无聊
# 2 楼答案
另一个解决方案使用
streams
并考虑negative
一位数