search
HomeJavajavaTutorialJava Collection Methods

The following article provides an outline for Java Collection Methods. The Java Collections Framework has a member called collections class. The collection class is contained in a package called java.util package. Mainly, the collection class is used along with the static methods which operate on return the collections or on the collections. Each and every method of this class throws the null pointer exception whenever the object or collection passed to any of the methods is null. There are three fields in the collection class, which are Empty_Map, EMPTY_LIST, EMPTY_SET, which can be used to get an immutable set, list, and map.

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

List of Java Collection Methods

Given below is the list of Java Collection Methods:

1. addAll() Method

Java.util.Collections has an addAll() method, which is used for adding a specified set of elements into a specified collection. Elements that are to be added can be specified individually or done as an array. This convenience method is same as the c.addAll(Arrays.asList(elements)), however the addAll() method is faster while doing most of the implementations.

Code:

import java.util.*;
public class EDUCBA {
public static void main(String[] course) throws Exception
{
try {
List<string> courselist = new ArrayList<string>();
courselist.add("Data Science");
courselist.add("Data Engineering");
courselist.add("Data Analyst");
courselist.add("Data Mining");
System.out.println("\n New Course List with course name : \n" + courselist);
boolean price = Collections.addAll(courselist, "22590", "23490", "34590", "54590");
System.out.println("\n Status of the courses on Website : \n" + price);
System.out.println("\n New Courses with their respective prices : \n" + courselist);
}
catch (NullPointerException upcomingcourse) {
System.out.println("Upcoming Courses are : " + upcomingcourse);
}
catch (IllegalArgumentException upcomingcourse) {
System.out.println("Upcoming Courses are : " + upcomingcourse);
}
}
}</string></string>

Output:

Java Collection Methods

Java Collection Methods

2. asLifoQueue() Method

The java.util.Collections class has asLifoQueue() method, which is used for returning a view of Deque as Last in first out Queue. For pushing, the method add is mapped and remove is used for pop. This method is majorly important when we require a queue in a Lifo ordering.

Code:

import java.util.*;
public class EDUCBA {
public static void main(String[] course) throws Exception
{
try {
Deque<string> courselist = new ArrayDeque<string>(10);
courselist.add("Data Science");
courselist.add("Data Analysis");
courselist.add("Data Engineering");
courselist.add("Data Mining");
Queue<string> newcourses = Collections.asLifoQueue(courselist);
System.out.println("\n New courses added to website are : \n" + newcourses);
}
catch (IllegalArgumentException upcomingcourses) {
System.out.println("\n Upcoming courses are : \n" + upcomingcourses);
}
}
}</string></string></string>

Output:

Java Collection Methods

Java Collection Methods

3. Collections.binarySearch() Method

The java.util.Collections have a method java.util.Collections.binarySearch(), which is used to return a specific object’s position in a sorted list. A ClassCastException is thrown by the method when the elements of the list are incomparable by using the specified comparator or when the search key is incomparable to the elements.

Code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class EDUCBA {
public static void main(String[] course)
{
List<integer> newcourseID = new ArrayList<integer>();
newcourseID.add(112202);
newcourseID.add(230042);
newcourseID.add(340713);
newcourseID.add(104219);
newcourseID.add(628973);
int IDofCourse = Collections.binarySearch(newcourseID, 340713);
System.out.println(IDofCourse);
IDofCourse = Collections.binarySearch(newcourseID, 628974);
System.out.println(IDofCourse);
}
}</integer></integer>

Output:

Java Collection Methods

Java Collection Methods

4. checkedCollection() Method

The java.util.Collections class has a checkedCollection() method, which is used for returning a dynamic typesafe view of a particular collection. hashCodes are not passed by the returned collection and equate the operations to the backing collection. However, it generally rely on hashCode methods and Object’s equals.

Code:

import java.util.*;
public class EDUCBA {
public static void main(String[] course) throws Exception
{
try {
List<string> courselist = new ArrayList<string>();
courselist.add("Data Science");
courselist.add("Data Analysis");
courselist.add("Data Engineering");
courselist.add("Data Mining");
System.out.println("\n Best seller courses: \n" + courselist);
Collection<string>
bestseller = Collections
.checkedCollection(courselist, String.class);
System.out.println("\n List constitues of bestseller courses, as: \n" + bestseller);
}
catch (IllegalArgumentException upcomingcourses) {
System.out.println("\n Upcoming courses are : \n" + upcomingcourses);
}
}
}</string></string></string>

Output:

Java Collection Methods

Java Collection Methods

5. copy() Method

The java.util.Collections class has a copy() method used to copy the elements of a list to another list.

Code:

import java.util.*;
public class EDUCBA {
public static void main(String[] course)
throws Exception
{
try {
List<string> courselist = new ArrayList<string>(10);
List<string> pricelist = new ArrayList<string>(10);
courselist.add("Data Science");
courselist.add("Data Analysis");
courselist.add("Data Engineering");
courselist.add("Data Mining");
pricelist.add("11900");
pricelist.add("23450");
pricelist.add("36340");
pricelist.add("44740");
System.out.println("\n Recently added courses: \n" + courselist);
System.out.println("\n Price of respective courses: \n" + pricelist);
System.out.println("\n Merging these above lists: \n");
Collections.copy(pricelist, courselist);
System.out.println(" Recently added courses: " + courselist);
System.out.println("\n Price of respective courses, will be displayed shortly: " + pricelist);
}
catch (IllegalArgumentException upcomingcourse) {
System.out.println("\n Upcoming courses are : \n" + upcomingcourse);
}
catch (IndexOutOfBoundsException upcomingcourse) {
System.out.println("\n Upcoming courses are : \n" + upcomingcourse);
}
}
}</string></string></string></string>

Output:

Java Collection Methods

Java Collection Methods

Java Collection Methods

6. Java.util.Collections.disjoint() Method

The java.util.Collections class has java.util.Collections.disjoint() method used to check if two specified collections are a disjoint or if they are not. Disjoint is a condition when two collections don’t have any elements in common.

Code:

import java.util.*;
public class EDUCBA
{
public static void main(String[] course)
{
List<string> DataCourse = new ArrayList<string>();
DataCourse.add("Data Science");
DataCourse.add("Data Analysis");
DataCourse.add("Data Engineering");
DataCourse.add("Data Mining");
List<string> ColudCourse = new Vector<string>();
ColudCourse.add("AWS");
ColudCourse.add("Google Cloud");
ColudCourse.add("Azure");
ColudCourse.add("IBM Cloud");
List UpcomingCourses = new Vector();
UpcomingCourses.add(2);
UpcomingCourses.add("Waiting List");
System.out.println("\n You can buy bundle of DataCouse and CloudCourse : \n " +
Collections.disjoint(DataCourse, ColudCourse));
System.out.println("You can get deals on bundle of DataCouse and UpcomingCourses : \n " +
Collections.disjoint(DataCourse, UpcomingCourses));
}
}</string></string></string></string>

Output:

Java Collection Methods

Java Collection Methods

Conclusion

On the basis of this article, we understood the concepts of Java collection methods. This article explains various collection methods with examples. All of the methods mentioned in the article are thoroughly explained with their definitions and usage.

The above is the detailed content of Java Collection Methods. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

Java Features for Modern Development: A Practical OverviewJava Features for Modern Development: A Practical OverviewMay 08, 2025 am 12:12 AM

Javastandsoutinmoderndevelopmentduetoitsrobustfeatureslikelambdaexpressions,streams,andenhancedconcurrencysupport.1)Lambdaexpressionssimplifyfunctionalprogramming,makingcodemoreconciseandreadable.2)Streamsenableefficientdataprocessingwithoperationsli

Mastering Java: Understanding Its Core Features and CapabilitiesMastering Java: Understanding Its Core Features and CapabilitiesMay 07, 2025 pm 06:49 PM

The core features of Java include platform independence, object-oriented design and a rich standard library. 1) Object-oriented design makes the code more flexible and maintainable through polymorphic features. 2) The garbage collection mechanism liberates the memory management burden of developers, but it needs to be optimized to avoid performance problems. 3) The standard library provides powerful tools from collections to networks, but data structures should be selected carefully to keep the code concise.

Can Java be run everywhere?Can Java be run everywhere?May 07, 2025 pm 06:41 PM

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

What is the difference between JDK and JVM?What is the difference between JDK and JVM?May 07, 2025 pm 05:21 PM

JDKincludestoolsfordevelopingandcompilingJavacode,whileJVMrunsthecompiledbytecode.1)JDKcontainsJRE,compiler,andutilities.2)JVMmanagesbytecodeexecutionandsupports"writeonce,runanywhere."3)UseJDKfordevelopmentandJREforrunningapplications.

Java features: a quick guideJava features: a quick guideMay 07, 2025 pm 05:17 PM

Key features of Java include: 1) object-oriented design, 2) platform independence, 3) garbage collection mechanism, 4) rich libraries and frameworks, 5) concurrency support, 6) exception handling, 7) continuous evolution. These features of Java make it a powerful tool for developing efficient and maintainable software.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool