Operations on Collection Objects
Java Platform, Enterprise Edition (Java EE) 8
The Java EE Tutorial

Previous Next Contents

Operations on Collection Objects

The EL supports operations on collection objects: sets, lists, and maps. It allows the dynamic creation of collection objects, which can then be operated on using streams and pipelines.

Note:

Like lambda expressions, operations on collection objects are part of Java SE 8.

For example, you can construct a set as follows:

{1,2,3}

You can construct a list as follows; a list can contain various types of items:

[1,2,3]
[1, "two", [three,four]]

You can construct a map by using a colon to define the entries, as follows:

{"one":1, "two":2, "three":3}

You operate on collection objects using method calls to the stream of elements derived from the collection. Some operations return another stream, which allows additional operations. Therefore, you can chain these operations together in a pipeline.

A stream pipeline consists of the following:

  • A source (the Stream object)

  • Any number of intermediate operations that return a stream (for example, filter and map)

  • A terminal operation that does not return a stream (for example, toList())

The stream method obtains a Stream from a java.util.Collection or a Java array. The stream operations do not modify the original collection object.

For example, you might generate a list of titles of history books as follows:

books.stream().filter(b->b.category == 'history')
              .map(b->b.title)
              .toList()

The following simpler example returns a sorted version of the original list:

[1,3,5,2].stream().sorted().toList()

Streams and stream operations are documented in the Java SE 8 API documentation, available at http://docs.oracle.com/javase/8/docs/api/. The following subset of operations is supported by the EL:

allMatch
anyMatch
average
count
distinct
filter
findFirst
flatMap
forEach
iterator
limit
map
max
min
noneMatch
peek
reduce
sorted
substream
sum
toArray
toList

See the EL specification at http://www.jcp.org/en/jsr/detail?id=341 for details on these operations.


Previous Next Contents
Oracle Logo  Copyright © 2017, Oracle and/or its affiliates. All rights reserved.