JBUG- Collection

2014. 7. 30. 22:01Study/Study group


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 Iterators.

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:

.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:

.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()
    .collect(Collectors.joining(", "));

Or perhaps sum the salaries of all employees:

int total = employees.stream()

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)


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 an Iterator for a collection by calling its iterator method. The following is the Iterator interface.

public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove(); //optional

Use Iterator instead of the for-each construct when you need to:

  • Remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-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 arbitrary Collection — that is, traverse the collection removing specific elements.

static void filter(Collection<?> c) {
    for (Iterator<?> it = c.iterator(); it.hasNext(); )
        if (!cond(it.next()))

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 — returns true if the target Collection contains all of the elements in the specified Collection.
  • addAll — adds all of the elements in the specified Collection to the target Collection.
  • removeAll — removes from the target Collection all of its elements that are also contained in the specified Collection.
  • retainAll — removes from the target Collection all its elements that are not also contained in the specified Collection. That is, it retains only those elements in the target Collection that are also contained in the specified Collection.
  • clear — removes all elements from the Collection.

The addAllremoveAll, and retainAll methods all return true if the target Collection 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 aCollectionc.


More specifically, suppose you want to remove all of the null elements from a Collection.


This idiom uses Collections.singleton, which is a static factory method that returns an immutable Set 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 a Collection to be translated into an array. The simple form with no arguments creates a new array of Object. 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 a Collection. The following snippet dumps the contents of c into a newly allocated array of Object whose length is identical to the number of elements in c.

Object[] a = c.toArray();

Suppose that c is known to contain only strings (perhaps because c is of type Collection<String>). The following snippet dumps the contents of cinto a newly allocated array of String whose length is identical to the number of elements in c.

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);
Set<Type> intersection = new HashSet<Type>(s1);
Set<Type> difference = new HashSet<Type>(s1);

두개의 Set 대칭차집합 = 합집합 - 교집합