distinctValuesOfArray
返回数组的所有不同值。
使用 Arrays.stream().distinct()
去除所有重复的值。
public static int[] distinctValuesOfArray(int[] elements) {
return Arrays.stream(elements).distinct().toArray();
}
dropElements
移除数组中的元素,直到传递的函数返回true为止。返回数组中的其余元素。
使用数组循环遍历数组,将数组的第一个元素删除,直到函数返回的值为真为止。返回其余的元素。
public static int[] dropElements(int[] elements, IntPredicate condition) {
while (elements.length > 0 && !condition.test(elements[0])) {
elements = Arrays.copyOfRange(elements, 1, elements.length);
}
return elements;
}
dropRight
返回一个新数组,从右边移除n个元素。
检查n是否短于给定的数组,并使用 Array.copyOfRange()
以便对其进行相应的切片或返回一个空数组。
public static int[] dropRight(int[] elements, int n) {
if (n < 0) {
throw new IllegalArgumentException("n is less than 0");
}
return n < elements.length
? Arrays.copyOfRange(elements, 0, elements.length - n)
: new int[0];
}
everyNth
返回数组中的每个第n个元素。
使用 IntStream.range().filter()
创建一个新数组,该数组包含给定数组的每个第n个元素。
public static int[] everyNth(int[] elements, int nth) {
return IntStream.range(0, elements.length)
.filter(i -> i % nth == nth - 1)
.map(i -> elements[i])
.toArray();
}
indexOf
查找数组中元素的索引,在不存在元素的情况下返回-1。
使用 IntStream.range().filter()
查找数组中元素的索引。
public static int indexOf(int[] elements, int el) {
return IntStream.range(0, elements.length)
.filter(idx -> elements[idx] == el)
.findFirst()
.orElse(-1);
}