public
interface
Collection<E>...
In JDK 8 and later, the
Collection
interface also exposes methods Stream<E> stream()
and Stream<E> parallelStream()
, for obtaining sequential or parallel streams from the underlying collection. (See the lesson entitled Aggregate Operations for more information about using streams.)
Traversing Collections
There are three ways to traverse collections: (1) using aggregate operations (2) with the for-each
construct and (3) by using Iterator
s.
Aggregate Operations
In JDK 8 and later, the preferred method of iterating over a collection is to obtain a stream and perform aggregate operations on it. Aggregate operations are often used in conjunction with lambda expressions to make programming more expressive, using less lines of code. The following code sequentially iterates through a collection of shapes and prints out the red objects:
myShapesCollection.stream()
.filter(e -> e.getColor() == Color.RED)
.forEach(e -> System.out.println(e.getName()));
Likewise, you could easily request a parallel stream, which might make sense if the collection is large enough and your computer has enough cores:
myShapesCollection.parallelStream()
.filter(e -> e.getColor() == Color.RED)
.forEach(e -> System.out.println(e.getName()));
There are many different ways to collect data with this API. For example, you might want to convert the elements of a Collection
to String
objects, then join them, separated by commas:
String joined = elements.stream()
.map(Object::toString)
.collect(Collectors.joining(", "));
Or perhaps sum the salaries of all employees:
int total = employees.stream()
.collect(Collectors.summingInt(Employee::getSalary)));
These are but a few examples of what you can do with streams and aggregate operations. For more information and examples, see the lesson entitled Aggregate Operations.
for-each Construct
The for-each
construct allows you to concisely traverse a collection or array using a for
loop — see The for Statement. The following code uses thefor-each
construct to print out each element of a collection on a separate line.
for (Object o : collection)
System.out.println(o);
Iterators
An
Iterator
is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired. You get anIterator
for a collection by calling itsiterator
method. The following is theIterator
interface.public interface Iterator<E> { boolean hasNext(); E next(); void remove(); //optional }
Use
Iterator
instead of thefor-each
construct when you need to:
- Remove the current element. The
for-each
construct hides the iterator, so you cannot callremove
. Therefore, thefor-each
construct is not usable for filtering.- Iterate over multiple collections in parallel.
The following method shows you how to use an
Iterator
to filter an arbitraryCollection
— that is, traverse the collection removing specific elements.static void filter(Collection<?> c) { for (Iterator<?> it = c.iterator(); it.hasNext(); ) if (!cond(it.next())) it.remove(); }
Collection Interface Bulk Operations
Bulk operations perform an operation on an entire
Collection
. You could implement these shorthand operations using the basic operations, though in most cases such implementations would be less efficient. The following are the bulk operations:
containsAll
— returnstrue
if the targetCollection
contains all of the elements in the specifiedCollection
.addAll
— adds all of the elements in the specifiedCollection
to the targetCollection
.removeAll
— removes from the targetCollection
all of its elements that are also contained in the specifiedCollection
.retainAll
— removes from the targetCollection
all its elements that are not also contained in the specifiedCollection
. That is, it retains only those elements in the targetCollection
that are also contained in the specifiedCollection
.clear
— removes all elements from theCollection
.The
addAll
,removeAll
, andretainAll
methods all returntrue
if the targetCollection
was modified in the process of executing the operation.As a simple example of the power of bulk operations, consider the following idiom to remove all instances of a specified element,
e
, from aCollection
,c
.c.removeAll(Collections.singleton(e));More specifically, suppose you want to remove all of the
null
elements from aCollection
.c.removeAll(Collections.singleton(null));This idiom uses
Collections.singleton
, which is a static factory method that returns an immutableSet
containing only the specified element.Collection Interface Array Operations
The
toArray
methods are provided as a bridge between collections and older APIs that expect arrays on input. The array operations allow the contents of aCollection
to be translated into an array. The simple form with no arguments creates a new array ofObject
. The more complex form allows the caller to provide an array or to choose the runtime type of the output array.For example, suppose that
c
is aCollection
. The following snippet dumps the contents ofc
into a newly allocated array ofObject
whose length is identical to the number of elements inc
.Object[] a = c.toArray();Suppose that
c
is known to contain only strings (perhaps becausec
is of typeCollection<String>
). The following snippet dumps the contents ofc
into a newly allocated array ofString
whose length is identical to the number of elements inc
.String[] a = c.toArray(new String[0]);Set - 수학에서의 집합을 모델링 함.
LIST - 리스트
MAP - y=f(x) 을 모델링 key가 x, value가 y 임.
찾아보기 : red-black tree람다합집합Set<Type> union = new HashSet<Type>(s1);union.addAll(s2);교집합Set<Type> intersection = new HashSet<Type>(s1);intersection.retainAll(s2);차집합Set<Type> difference = new HashSet<Type>(s1);difference.removeAll(s2);두개의 Set 대칭차집합 = 합집합 - 교집합
'Study > Study group' 카테고리의 다른 글
k8s 스터디 흔적 (0) | 2020.10.22 |
---|---|
2020.07.16 스터디 (0) | 2020.07.16 |
JBUG - JDK8 Study (2) | 2014.07.23 |
JBUG - JDK8 Study(정규표현식)- Differences Among Greedy, Reluctant, and Possessive Quantifiers (0) | 2014.07.17 |
JBUG - JDK8 Study(Concurrency_01) (2) | 2014.07.03 |