Home » Java Collection retainAll() Method with Examples

Java Collection retainAll() Method with Examples

by Online Tutorials Library

Java Collection retainAll() method

The retainAll() method of Java Collection Interface keeps only those elements in this queue that are present in the specified collection.

Syntax

Parameters

The parameter ‘c’ represents the collection having elements to be kept in this collection.

Return Value

The retainAll() method returns true if this collection changes as a result of the call.

Throws

The retainAll() method throws:

UnsupportedOperationException– if the retainAll operation is not supported by this collection.

ClassCastException– if the types of one or more elements in this collection are not compatible with the specified collection.

NullPointerException– if this collection is null or it contains one or more null elements and the invoked collection does not allow null elements.

Example 1

Test it Now

Output:

collection : [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z] Vowels : [a, e, i, o, u] 

Example 2

Test it Now

Output:

Total no : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]  Table of 2 : [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] 

Example 3

Test it Now

Output:

Exception in thread "main" java.lang.NullPointerException at java.util.Objects.requireNonNull(Objects.java:203) at java.util.AbstractCollection.retainAll(AbstractCollection.java:405) at com.tutorAspire.JavaCollectionRetainAllExample4.main(JavaCollectionRetainAllExample4.java:17) 

Java Collection retainAll() Method

The retainAll() method of Java Collection class retains or keeps only the elements in this collection that are contained in the invoked collection and removes all the elements that are not contained in the specified collection.

Syntax

Parameters

The parameter ‘c’ represents the collection which contains the elements to be retained in this collection.

Return Value:

The retainAll () method returns a Boolean value ‘true’ if this collection has changed as a result of this call.

Throws

UnsupportedOperationException– if the retainAll method is not supported by this collection.

ClassCastException– if the types of one or more elements in this collection are not compatible with the invoked collection.

NullPointerException– if this collection is null or it contains one or more null elements and the specified collection does not allow null elements.

Example 1

Test it Now

Output:

collection : [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z] Vowels : [A, E, I, O, U] 

Example 2

Test it Now

Output:

collection : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,  22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,  44, 45, 46, 47, 48, 49, 50] Vowels : [5, 10, 15, 20, 25, 30, 35, 40, 45, 50] 
Next TopicJava-Collection

You may also like