Collection新增方法:
- removeIf
- stream
- parallelStream
- spliterator
list中
- replaceAll
- sort
removeIf
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
作用是删除容器中所有满足filter指定条件的元素
比如:
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9);
// 删除列表中大于5的数
list.removeIf(item -> item > 5);
System.out.println(list.toString());
// [1, 2, 3, 4, 5]
replaceAll
default void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final ListIterator<E> li = this.listIterator();
while (li.hasNext()) {
li.set(operator.apply(li.next()));
}
}
作用是对每个元素执行operator指定的操作,并用操作结果来替换原来的元素
比如:
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9);
list.replaceAll(item -> {
return item > 5 ? item +5 : item ;
});
System.out.println(list.toString());
// [1, 2, 3, 4, 5, 11, 12, 13, 14]
sort
default void sort(Comparator<? super E> c) {
Object[] a = this.toArray();
Arrays.sort(a, (Comparator) c);
ListIterator<E> i = this.listIterator();
for (Object e : a) {
i.next();
i.set((E) e);
}
}
比如:
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9);
// 正序
list.sort((a1, a2) -> a1 - a2);
System.out.println(list.toString());
// 倒序
Comparator<Integer> comparator = (a1, a2) -> a2.compareTo(a1);
list.sort(comparator.reversed());
System.out.println(list.toString());
spliterator
可分割的迭代器,不同以往的iterator需要顺序迭代,Spliterator可以分割为若干个小的迭代器进行并行操作,既可以实现多线程操作提高效率,又可以避免普通迭代器的fail-fast机制所带来的异常
stream和parallelStream
stream和parallelStream 分别返回该容器的Stream视图表示,不同之处在于parallelStream()返回并行的Stream。Stream是Java函数式编程的核心类