default void replaceAll(UnaryOperator<E> operator)
对于该方法,Java jdk1.8手册里是这么描述的 :用函数接口的返回结果替代原list中的值.
list 接口中的源码
default void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final ListIterator<E> li = this.listIterator();
while (li.hasNext()) {
li.set(operator.apply(li.next()));
}
}
arraylist 中的源码
public void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
elementData[i] = operator.apply((E) elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
其中,UnaryOperator<E> 这个类型,中文翻译了一下,是一元运算符的意思。
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
/**
* Returns a unary operator that always returns its input argument.
*
* @param <T> the type of the input and output of the operator
* @return a unary operator that always returns its input argument
*/
static <T> UnaryOperator<T> identity() {
return t -> t;
}
}
@FunctionalInterface这是个函数式接口注解,并且只能用一元操作符
List<Integer> numList = new ArrayList<>();
numList.add(1);
numList.add(2);
numList.add(3);
//这里将函数改成了t -> t + 1
numList.replaceAll(t -> t + 1);
for (int i = 0; i < numList.size(); i++) {
System.out.println(numList.get(i));
}
运行结果:
2 3 4
类似于这样的输入函数,都可以