Collection and Iterator interfaces of java collections, collectioniterator

Source: Internet
Author: User

Collection and Iterator interfaces of java collections, collectioniterator

 

Collection is the parent interface of the List, Queue, and Set interfaces. The methods defined in this interface can be used to operate the Set or List and Queue sets. The Collection interface defines the following methods for operating elements.

Boolean add (object o ):This method is used to add an element to a set. Returns true if the set object is changed by the add operation.

Boolean addAll (Collection c ):Add all elements in set c to the specified set. Returns true if the set object is changed by the add operation.

Void clear ():Clear all elements in the set and change the set length to 0.

Boolean contatins (Objeect o ):Returns whether the specified Element o is included in the collection. True is returned if it contains.

Boolean containsAll (Collection c ):Returns whether the set contains all elements in set c. True is returned if it contains.

Boolean isEmpty ():Whether the returned set is null. Returns true if the set length is zero. Otherwise, returns false.

Iterator iterator ():Returns an Iterator object used to traverse elements in the set.

Boolean remove (ObjectO): deletes the specified o element in the set. When the set contains multiple o elements, only the first o element that meets the condition is deleted. This method returns true.

Boolean removeAll (Collection c ):Delete all elements contained in set c in the Set (equivalent to the current set minus set c). If this method changes the set that calls this method, this method returns true.

Boolean retainAll (Collection c ):Delete all elements not contained in set c (equivalent to finding the intersection of the current set in set c). If this method changes the set that calls this method, return true.

Int size ():Returns the length of the set.

Object [] toArray ():Converts a set to an array. All the set elements are converted to corresponding array elements.

 

Public class CollectionTest {public static void main (String [] args) {Collection c = new ArrayList (); // Add element c. add ("Sun Wukong"); c. add (6); System. out. println ("the number of elements in the c set is:" + c. size (); // Delete the element c. remove (6); System. out. println ("the number of elements in the c set is:" + c. size (); System. out. println ("Whether the c collection contains 'Sun wukong':" + c. contains ("Sun Wukong"); c. add ("lightweight java application development"); System. out. println ("the element in the c set is:" + c); Collection books = new HashSet (); books. add ("lightweight java application development"); books. add ("Crazy java handout"); System. out. println ("does the c set fully include the set books:" + c. containsAll (books); c. removeAll (books); System. out. println ("the element in the c set is:" + c); // clear the c. clear (); System. out. println ("the element in the c set is:" + c); books. retainAll (c); System. out. println ("the elements in the books set are:" + books );}}

Use Lambda expressions to traverse a set:

Java 8 adds a foreach (Consumer action) interface to the Iterble interface. The parameter type required for this method is a functional interface, and Iterable is the parent interface of the Collection interface, this method can be called directly for this Collection.

When the program calls the Iterable foreach (Consumer action) to traverse the collection elements, the program will pass the collection elements to the Comsumer accept (T t) method in sequence (the only abstract method in this method ).

Public class CollectionEach {public static void main (String [] args) {Collection books = new HashSet (); books. add ("lightweight java Enterprise Application Development"); books. add ("Crazy java handout"); books. add ("crazy android");/* output: iteration set: Crazy java handout iteration set: lightweight java Enterprise Application Development iteration set: crazy android */books. forEach (obj-> System. out. println ("Iteration set:" + obj ));}}

Use the Java 8 enhanced Ieteraor to traverse the set elements:

The Iteraor interface is also a member of the java Collection framework and is mainly used to traverse elements in the Collection set. The Iterator object is also called an Iterator.

Iteraor defines some methods:

Boolean hasnext ():Returns true if the element to be iterated has not been completely traversed.

Object next ():Returns the next element in the set.

Void remove ():Delete the elements returned by the next method in the collection.

Void forEachRemning (Consumer action ):Use a Lambda expression to traverse a set.

When Iterator is used to iteratively Access Collection set elements, the elements in the Collection set cannot be changed. Only the Collection elements returned by the last next () method can be deleted through the remove Method of Iterator, otherwise, an exception is thrown.

Public class IteratorTest2 {public static void main (String [] args) {Collection books = new HashSet (); books. add ("lightweight java Enterprise Application Development"); books. add ("Crazy java handout"); books. add ("crazy android"); Iterator it = books. iterator (); while (it. hasNext () {String book = (String) it. next (); // output: Crazy java handout
// Lightweight java Enterprise Application Development
// Crazy android
System. out. println (book); if (book. equals ("Crazy java handout") {it. remove () ;}// output: [lightweight java Enterprise Application Development, crazy android]
System. out. println (books );}}

Traverse Iterator using Lambda expressions

Java 8 provides a forEachRemning (Consumer action) method for Iterator. The required Consumer parameter is also a functional interface. When the program calls the forEachRemning (Consumer action) of the Iterator to traverse the collection elements, the program sends the collection elements to the accept (T t) method of the Consumer in sequence (the only method in this interface ).

Public class IteratorEach {public static void main (String [] args) {Collection books = new HashSet (); books. add ("lightweight java Enterprise Application Development"); books. add ("Crazy java handout"); books. add ("crazy android"); Iterator it = books. iterator ();/* iteration Element Set: Crazy java handout iteration Element Set: lightweight java Enterprise Application Development iteration Element Set: crazy android */it. forEachRemaining (obj-> System. out. println ("iterations Element Set:" + obj ));}}

Use foreach to traverse collection elements cyclically

In addition to the Iterator interface, you can use the foreach loop provided by Java 5 to iteratively access the elements in the Collection set.

Public class ForeachTest {public static void main (String [] args) {Collection books = new HashSet (); books. add ("lightweight java Enterprise Application Development"); books. add ("Crazy java handout"); books. add ("crazy android"); for (Object obj: books) {String book = (String) obj;/* Crazy java handout lightweight java Enterprise Application Development crazy android */System. out. println (book); if (book. equals ("Crazy Andriod handout") {// the following code will throw an exception to books. remove (book) ;}/// [Crazy java handout, lightweight java Enterprise Application Development, crazy android] System. out. println (books );}

Use the Prdicate operation set added by Java 8:

Java 8 adds a removeIf (Predicate filter) method to the Collectio set. This method deletes all elements that meet the filter conditions in batches.

Public class PredicateTest {public static void main (String [] args) {Collection books = new HashSet (); books. add (new String ("lightweight java application development"); books. add (new String ("Crazy java handout"); books. add (new String ("Crazy IOS handout"); books. add (new String ("Crazy Ajax handout"); books. add (new String ("crazy android handout"); // counts the number of books whose titles include "crazy" substrings. output: 4 System. out. println (calAll (books, ele-> (String) ele ). contains ("crazy"); // counts the number of books whose name string length is greater than 10. output: 2 System. out. println (calAll (books, ele-> (String) ele ). length ()> 10);} public static int calAll (Collection books, Predicate p) {int total = 0; for (Object obj: books) {if (p. test (obj) {total ++ ;}} return total ;}}

 Use the Stream operation set added by Java 8:

Stream, IntStream, LongStream, and DoubleStream APIs are added to Java 8. These APIs represent multiple elements that support serial and parallel aggregation operations. In the preceding four interfaces, Stream represents a universal Stream interface, while others represent streams with element types of int, long, and double respectively.

Independent stream usage:

1. Use the builder () Class Method of Stream or Xxxstream to create the Builder corresponding to the Stream.

2. Call the add () method of Budiler repeatedly to add multiple elements to the stream.

3. Call the build () method of Builder to obtain the corresponding Stream.

4. Call the Stream aggregation method.

For most clustering methods, each Stream can be executed only once.

Stream provides a large number of methods for clustering operations. These methods can be either "intermediate" or "terminal".

> Intermediate method: the intermediate operation allows the stream to be kept open and can directly call subsequent methods. The Return Value of the intermediate method is another stream.

> End method: the end method is the final operation of convection. When the end method is executed on a Stream object, the Stream is "consumed" and cannot be reused.

In addition, the stream method has the following two features:

1. stateful method: This method adds some new features to the stream, such as the uniqueness of elements, the maximum number of elements, and ensures that elements are processed in order. Stateful methods often require greater overhead.

2. Short-Circuit Method: the short-circuit method can terminate the convection operation as soon as possible without checking each element.

Common intermediate Stream methods:

Filter (Predicate predicate ):Filter all elements that do not conform to predicate.

Map ToXxx (ToXxxFunction mapper ):Use ToXxxFunction to perform one-to-one conversion on the elements in the stream, and return a new stream containing the elements generated after the conversion.

Peek (Consumer action ):Perform operations on each element in sequence. The returned stream of this method contains the same elements as the original stream. This method is mainly used for debugging.

Distinct ():This method is used to sort repeated elements in a stream (the criterion for determining repeated elements is to use the equals () method to compare and return true ). This is a stateful method.

Sorted ():This method ensures that the elements in the stream are in order in subsequent operations. This is a stateful method.

Limit (long maxSize ):This method is used to ensure the maximum number of elements allowed for subsequent streaming access. This is a stateful, short-circuit method.

Common end methods:

ForEach (Consumer action ):Traverse the elements in the stream and execute actions on each element.

ToArray ():Converts all elements in the stream to an array.

Reduce ():This method has three overloaded versions, all of which are used to merge elements in the stream through some operation.

Min ():Returns the minimum value of an element in a stream.

Max ():Returns the maximum value of an element in a stream.

Count ():Returns the value of the element used in the stream.

AnyMatch (Predicate predicate ):Determines whether a stream contains at least one Predicate condition.

AllMatch (Predicate predicate ):Determine whether each element in the stream meets the Predicate condition.

NoneMatch (Predicate predicate ):Determines whether all elements in a stream do not include the operator and Predicate conditions.

FindFirst ():Returns the first element in the stream.

FindAny ():Returns any element in the stream.

Public class CollectionStream {public static void main (String [] args) {Collection books = new HashSet (); books. add (new String ("lightweight java application development"); books. add (new String ("Crazy java handout"); books. add (new String ("Crazy IOS handout"); books. add (new String ("Crazy Ajax handout"); books. add (new String ("crazy android handout"); // counts the number of books in the book that contain "crazy" substrings. // output: 4 System. out. println (books. stream (). filter (ele-> (String) ele ). contains ("crazy ")). count (); // count the number of books that contain the "java" substring In the title. // output: 2 System. out. println (books. stream (). filter (ele-> (String) ele ). contains ("java ")). count (); // number of books whose string length is greater than 10 in the graph. // output: 2 System. out. println (books. stream (). filter (ele-> (String) ele ). length ()> 10 ). count ();/* First call the stream method of the Collection object to convert the set to Stream * and then call the mapToXxx () method in Stream to convert */books. stream (). mapToInt (ele-> (String) ele ). length () // use the forEach method to traverse each element in IntStream // output: 8 8 7 11. forEach (System. out: println );}}

--------- Crazy java handout 8.2

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.