今天心情有点粉,来学学 Collection 吧!
int size()
boolean isEmpty()
boolean contains(Object element)
boolean add(E element)
boolean remove(Object element)
Iterator<E> iterator()
boolean containsAll(Collection<?> c)
boolean addAll(Collection<? extends E> c)
boolean removeAll(Collection<?> c)
boolean retainAll(Collection<?> c)
void clear()
Object[] toArray()
<T> T[] toArray(T[] a)
Stream<E> stream()
Stream<E> parallelStream()
for-each
语法
Collection<Person> persons = new ArrayList<Person>(); for (Person person : persons) { System.out.println(person.name); } Iterator
迭代器
Collection<Person> persons = new ArrayList<Person>(); Iterator iterator = persons.iterator(); while (iterator.hasNext) { System.out.println(iterator.next); } aggregate operations
聚合操作
Collection<Person> persons = new ArrayList<Person>(); persons .stream() .forEach(new Consumer<Person>() { @Override public void accept(Person person) { System.out.println(person.name); } }); 1.使用流来遍历一个 ShapesCollection,然后输出红色的元素:
myShapesCollection.stream()
.filter(e -> e.getColor() == Color.RED)
.forEach(e -> System.out.println(e.getName()));
2.你还可以获取一个并行流(parallelStream),当集合元素很多时使用并发可以提高效率:
myShapesCollection.parallelStream()
.filter(e -> e.getColor() == Color.RED)
.forEach(e -> System.out.println(e.getName()));
3.聚合操作还有很多操作集合的方法,比如说你想把 Collection 中的元素都转成 String 对象,然后把它们 连起来:
String joined = elements.stream()
.map(Object::toString)
.collect(Collectors.joining(", "));
看起来是不是非常简洁呢!
public static void filter(Collection<?> c) {
for (Iterator<?> it = c.iterator(); it.hasNext(); )
if (!condition(it.next()))
it.remove();
}
并行”是指无论从微观还是宏观,二者都是一起执行的,就好像两个人各拿一把铁锨在挖坑,一小时后,每人一个大坑。 而“并发”在微观上不是同时执行的,只是把时间分成若干段,使多个进程快速交替的执行,从宏观外来看,好像是这些进程都在执行,这就好像两个人用同一把铁锨,轮流挖坑,一小时后,两个人各挖一个小一点的坑,要想挖两个大一点得坑,一定会用两个小时。 从以上本质不难看出,“并发”执行,在多个进程存在资源冲突时,并没有从根本提高执行效率。 http://zhidao.baidu.com/link?url=1L6YSAULAhjLH4ZYfO0yCbKlvo8DJeQMtCmCLKYpENStbpxNDiFCwaJf4iZaNDr7cho37GctXOddek3LhrO3_K
https://docs.oracle.com/javase/tutorial/collections/intro/index.html
https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
http://joearms.github.io/2013/04/05/concurrent-and-parallel-programming.html