Java Reference
In-Depth Information
Methods for Aggregate Operations
Java 8 added support for aggregate operations on collections through streams. A stream is a sequence of elements
that supports sequential and parallel aggregate operations such as computing the sum of all elements of a collection
whose elements are integers. Streams are a vast topic and I will discuss them in Chapter 13. A stream is an instance of
the Stream interface. The Stream interface is in the java.util.stream package. You can create a Stream object from a
collection using the following methods of the Collection interface:
default Stream<E> stream() : Returns a sequential Stream with the collection as the source
of elements for the Stream .
default Stream<E> parallelStream() : Returns a possibly parallel Stream with the collection
as the source of elements for the Stream .
Methods for Array Operations
Methods for array operations let you convert a collection into an array. The following are the methods in this category:
Object[] toArray() : Returns the elements of the collections in an array.
<T> T[] toArray(T[] a) : Returns an array of the specified type T that contains all elements
of the collection. If the passed-in array length is equal to or greater than the size of the
collection, all elements are copied to the passed-in array and the same array is returned.
Any extra elements in the array are set to null. If the passed-in array's length is less that the
size of the collection, it creates a new array of type T whose length is equal to the size of the
collection, copies all elements of the collection to the new array, and returns the new array.
Methods for Comparison Operations
Methods for comparison operations let you compare two collections for equality. The following are the methods in
this category:
boolean equals(Object o) : Returns true if two collections are equal. Otherwise, returns
false. The specific collection type specifies the criteria for equality of two collections.
int hashCode() : Returns the hash code for the collection. Suppose c1 and c2 are references of
two collections. If c1.equals(c2) returns true , c1.hashCode() == c2.hashCode() must also
return true .
A Quick Example
Before I discuss different types of collections, I will present a quick example of using a list that is a collection of
objects. A list is an ordered list of objects. An instance of the List<E> interface represents a list. The ArrayList<E>
class is an implementation of the List<E> interface. The program in Listing 12-1 creates a list to store names and
manipulates the list using different methods of the Collection interface.
The program uses the add() method to add some names to the list. It uses the remove() method to remove a
name from the list. The clear() method is used to remove all names from the list. At every stage, the program prints
the size of the list and the elements in the list.
 
Search WWH ::




Custom Search