一个Collection(集合)表示一组称为其元素的对象。Collection接口用来传递需要最大通用性的对象集合。例如,按约定,所有集合实现都有一个接收Collection的构造函数,称为转换构造函数,因此可以转换集合的类型。
例如,有一个 Collection<String> c,可能是List或Set,创建一个ArrayList:
List<String> list = new ArrayList<String>(c);
// JDK 7 or later
List<String> list = new ArrayList<>(c);
Collection接口的基本方法
int size()
boolean isEmpty()
boolean contains(Object element),
boolean add(E element)
boolean remove(Object element)
and Iterator<E> iterator()
Collection接口操作整个集合的方法
boolean containsAll(Collection<?> c),
boolean addAll(Collection<? extends E> c)
boolean removeAll(Collection<?> c)
boolean retainAll(Collection<?> c)
and void clear()
Collection接口的数组方法
Object[] toArray()
<T> T[] toArray(T[] a)
JDK 8 及其之后, Collection接口暴露了 Stream<E> stream() 和 Stream<E> parallelStream()方法,用于从基础集合获取顺序流或并行流。(参考 聚合操作)
遍历 Collections
三种方式:聚合操作,for-each,Iterator
聚合操作
JDK 8 及之后,推荐获取流执行聚合的方式遍历集合。
myShapesCollection.stream()
.filter(e -> e.getColor() == Color.RED)
.forEach(e -> System.out.println(e.getName()));
如果集合足够大且电脑核心数足够,可以使用并行流:
myShapesCollection.parallelStream()
.filter(e -> e.getColor() == Color.RED)
.forEach(e -> System.out.println(e.getName()));
多种方式收集数据:
String joined = elements.stream()
.map(Object::toString)
.collect(Collectors.joining(", "));
int total = employees.stream()
.collect(Collectors.summingInt(Employee::getSalary)));
for-each
for (Object o : collection)
System.out.println(o);
Iterators
Iteratos接口,remove方法只能每次调用next后调用一次,否则会报错。
Iterator.remove是在迭代期间,唯一安全的删除元素的方法。
public interface Iterator<E> {
boolean hasNext();
E next();
void remove(); //optional
}
使用Iterator而不是for-eahc的情况:
- 删除当前元素;
- 并行迭代多个集合。
static void filter(Collection<?> c) {
for (Iterator<?> it = c.iterator(); it.hasNext(); )
if (!cond(it.next()))
it.remove();
}
Collection批量操作
大多情况下这些操作的效率较低。
boolean containsAll(Collection<?> c),
boolean addAll(Collection<? extends E> c)
boolean removeAll(Collection<?> c)
boolean retainAll(Collection<?> c)
and void clear()
例如,从Collection c中删除所有 e:
c.removeAll(Collections.singleton(e));
删除所有null:
c.removeAll(Collections.singleton(null));
Collections.singleton,一个静态方法,返回包含指定元素的不可变Set。
Collection接口Array 操作
toArray作为集合和旧api之间的桥梁,旧api希望在输入时使用数组。
将Collection转为与之长度一致的数组。
无参数时,返回一个Object数组
Object[] a = c.toArray();
如果是Collection<String>
String[] a = c.toArray(new String[0]);
网友评论