The Wayback Machine - https://web.archive.org/web/20240822105424/https://www.geeksforgeeks.org/how-to-print-a-collection-in-java/
Open In App

How to Print a Collection in Java?

Last Updated : 24 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Collection is a set of objects that hold references to other objects in the program. In doing the same we already have studied a data structure- HashMap which internally works out the same way. So we come up with one of the approaches to print a Collection in java that is through HashMap. Now a step further we encounter- a collection framework.

The toString method is inherited by all the Classes in Java in order to print any collection in Java by overriding the toString method. After overriding, we can iterate through the collection using a for-each loop to print all the objects of the collection

Collections in java can be printed through 2 approaches which are:

  • Printing a user-defined ArrayList
  • Printing a user-defined HashMap

Approach 1: Printing a user-defined ArrayList

  • Create an ArrayList of the user-defined objects and populate the ArrayList.
  • Overrider the toString() method in the user-defined class to print the item of the ArrayList in the desired format.
  • Run a for-loop to print the objects.

Example

Java




// Java Program to print an arraylist of an
// user-defined collection
 
import java.util.*;
 
class GFG {
 
    String name;
    int rollNo;
 
    // constructor of class GFG
    GFG(String s, int n)
    {
        name = s;
        rollNo = n;
    }
 
    // over-riding the toString method
    // to print the collection
    public String toString()
    {
        return "Name : " + name + " | Roll No : " + rollNo;
    }
 
    // Driver Main Method
    public static void main(String[] args)
    {
        // creating an arraylist of user-defined collection
        ArrayList<GFG> arr = new ArrayList<GFG>();
 
        // creating objects of class GFG
        GFG t1 = new GFG("John", 101);
        GFG t2 = new GFG("Paul", 102);
        GFG t3 = new GFG("Jack", 103);
        GFG t4 = new GFG("Jose", 104);
 
        // adding objects to arraylist
        arr.add(t1);
        arr.add(t2);
        arr.add(t3);
        arr.add(t4);
 
        // printing the collection
        for (GFG c : arr)
            System.out.println(c);
    }
}


 
 

Output

Name : John | Roll No : 101
Name : Paul | Roll No : 102
Name : Jack | Roll No : 103
Name : Jose | Roll No : 10

Approach 2: Printing a user-defined HashMap

  • Create a hash map with user-defined key and value pair and fill the hash map using put() method.
  • Make sure to Override the toString() method in the user-defined class to print the items in the desired format.
  • Iterate over the hash map using the EntrySet() for loop and print the elements.

Example

Java




// Java program printing ArrayList
// of an user-defined collection
 
// Importing Classes/Files
import java.util.*;
 
public class GFG {
    String firstName;
    String lastName;
 
    // Constructor
    GFG(String fn, String ln)
    {
        firstName = fn;
        lastName = ln;
    }
 
    // Function- toString()
    public String toString()
    {
        // Over-riding the toString method to print the
        // collection
        return "| First Name : " + firstName
            + " | LastName : " + lastName;
    }
 
    // Driver Main Method
    public static void main(String[] args)
    {
        // Creating a hashmap with key as ID  and
        // value as user defined class
        HashMap<Integer, GFG> hm
            = new HashMap<Integer, GFG>();
 
        // creating objects
        GFG p1
            = new GFG("Mohit", "Singh");
        GFG p2
            = new GFG("Tarun", "Anand");
        GFG p3
            = new GFG("Madhu", "Singh");
        GFG p4
            = new GFG("Rohit", "Ahuja");
 
        // adding mappings
        hm.put(101, p1);
        hm.put(102, p2);
        hm.put(103, p3);
        hm.put(104, p4);
 
        // Iterating HashMap through for loop and printing the collection
        for (Map.Entry m : hm.entrySet())
            System.out.println(m.getKey() + " "
                               + m.getValue().toString());
    }
}


Output

101 | First Name : Mohit | LastName : Singh
102 | First Name : Tarun | LastName : Anand
103 | First Name : Madhu | LastName : Singh
104 | First Name : Rohit | LastName : Ahuja

 



Previous Article
Next Article

Similar Reads

Java Program to Get the Size of Collection and Verify that Collection is Empty
The size() and isEmpty() of java.util.Collection interface is used to check the size of collections and if the Collection is empty or not. isEmpty() method does not take any parameter and does not return any value. Example: Input:[99, 54, 112, 184, 2] Output:size = 5 and Collection is not empty Input:[] Output: size = 0 and Collection is emptysize(
2 min read
Java Program to Add the Data from the Specified Collection in the Current Collection
The grouping of objects in a single unit is called a collection. For example Array, Lists, Hashsets, etc. Data can be added from a specified collection in the current collection by using the addAll() method in Java. This method falls under the header file, java.util.*. The addAll() method returns a true value if the adding of the collection is succ
3 min read
Difference Between Collection.stream().forEach() and Collection.forEach() in Java
Collection.forEach() and Collection.stream().forEach() are used for iterating over the collections, there is no such major difference between the two, as both of them give the same result, though there are some differences in their internal working. Collection.stream().forEach() is basically used for iteration in a group of objects by converting a
3 min read
How to prevent objects of a class from Garbage Collection in Java
The garbage collector in Java is automatic, i.e the user doesn't have to manually free an occupied memory which was dynamically allocated. And how does a garbage collector decide which object is to be deleted? It's simple: the object which loses it's reference, is marked for deletion from the heap memory. For example, look at the following piece of
5 min read
Iterator vs Collection in Java
Iterator and Collection, both has helped and comforted the programmers at many a times. But their usage and application has a very wide difference. 1. Iterator Declaration public interface Iterator Type Parameters: E - the type of elements returned by this iteratorIterators are used in Collection framework in Java to retrieve elements one by one. M
3 min read
Convert an Iterable to Collection in Java
Iterable and Collection have served to be of great use in Java. Iterators are used in Collection framework in Java to retrieve elements one by one and a Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single
4 min read
Finding minimum and maximum element of a Collection in Java
A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit. These are: Finding minimum and maximum element of a Collection can be easily done using the Collections.min() and Collections.max() method. Thes
6 min read
Non-generic Vs Generic Collection in Java
We will be discussing differences later prior let us understand what is generic Collection and non-generic Collection, and most importantly dealing with the implementation part as during implementation one can only really get the real understanding of the concept, henceforth the differences between them. Generics are basically the errors appearing
5 min read
Collection addAll() method in Java with Examples
The addAll(Collection collection) of java.util.Collection interface is used to add the Collection 'collection' to this existing collection. This method returns a boolean value depicting the successfulness of the operation. If the collection was added, it returns true, else it returns false. Syntax: Collection.addAll(Collection&lt;E&gt; collection)
3 min read
Collection add() Method in Java with Examples
The add(E element) of java.util.Collection interface is used to add the element 'element' to this collection. This method returns a boolean value depicting the successfulness of the operation. If the element was added, it returns true, else it returns false. Syntax: Collection.add(E element) Parameters: This method accepts a mandatory parameter ele
4 min read
Collection contains() method in Java with Examples
The contains(Object element) of java.util.Collection interface is used to check whether the element 'element' exists in this collection. This method returns a boolean value depicting the presence of the element. If the element is present, it returns true, else it returns false. Syntax: Collection.contains(Object element) Parameters: This method acc
3 min read
Stack addAll(int, Collection) method in Java with Example
The addAll(int, Collection) method of Stack Class is used to append all of the elements from the collection passed as a parameter to this function at a specific index or position of a Stack. Syntax: boolean addAll(int index, Collection C) Parameters: This function accepts two parameters as shown in the above syntax and are described below. index: T
2 min read
Stack addAll(Collection) method in Java with Example
The addAll(Collection) method of Stack Class is used to append all of the elements from the collection passed as a parameter to this function to the end of a Stack keeping in mind the order of return by the collection's iterator. Syntax: boolean addAll(Collection C) Parameters: The method accepts a mandatory parameter C which is a collection of Arr
2 min read
How to Get a Size of Collection in Java?
Given a Collection in Java, the task is to find the length or size of the collection. Examples: Input: Array_List: [1, 2, 3,4] Output: 4 Input: Linked_List: [geeks, for, geeks] Output: 3 The Size of the different collections can be found with the size() method. This method returns the number of elements in this collection. This method does not take
2 min read
How to Add All Items From a Collection to an ArrayList in Java?
Given a Collection with some values, the task is to add all the items of this Collection to an ArrayList in Java. Illustrations: Input: Collection = [1, 2, 3] Output: ArrayList = [1, 2, 3]Input: Collection = [GFG, Geek, GeeksForGeeks] Output: ArrayList = [GFG, Geek, GeeksForGeeks] Approach: Get the Collection whose items are to be added into the Ar
2 min read
How to add selected items from a collection to an ArrayList in Java?
Given a Collection with some values, the task is to add selected the items of this Collection to an ArrayList in Java. Examples: Input: Collection = [1, 2, 3], condition = (item != 2) Output: ArrayList = [1, 3] Input: Collection = [GFG, Geek, GeeksForGeeks], condition = (item != GFG) Output: ArrayList = [Geek, GeeksForGeeks] Approach: Get the Colle
2 min read
Collecting a Stream to an Immutable Collection in Java
Streams and Collectors were introduced in Java 8 introduced the concept of Streams. A Stream is a sequence, a sequence of objects. We generate Streams from input sources like Arrays, Lists, etc., and support aggregation operations like filter, map, limit, reduce, etc. We use Streams to pipeline data and ultimately collect it into some form of a Col
6 min read
Java Program to Change a Collection to an Array
An array is a data structure that can hold a fixed-size, homogeneous collection of elements of the same data type, which can be either primitive data types (e.g., int, float) or object references. However, the size of the array cannot be changed once it is created. On the other hand, a collection is an interface in Java that defines a set of method
3 min read
Java Program to Remove a Specific Element From a Collection
remove() method is used to remove elements from a collection. It removes the element at the specified position in this list. Shifts any subsequent elements to the left by subtracts one from their indices. In simpler words, the remove() method is used for removing the element from a specific index from a list by removing the value and returning the
3 min read
Convert an Array into Collection in Java
Java Collection provides an architecture to store and manipulate a group of objects. The datatype of data can be changed to a general data type like array into Collection. To convert array-based data into Collection based we can use java. util. Arrays class. This class provides a static method asList(T... a) that converts the array into a Collectio
4 min read
Collection Interface in Java with Examples
The Collection interface is a member of the Java Collections Framework. It is a part of java.util package. It is one of the root interfaces of the Collection Hierarchy. The Collection interface is not directly implemented by any class. However, it is implemented indirectly via its subtypes or subinterfaces like List, Queue, and Set. For Example, th
8 min read
How to Make a Collection Read-Only in Java?
The Collections class is used as a data structure to manage the data. We can add, remove, fetch, and update the data in the List, Set, or Map Object. Collections class has default methods for these operations. We can use those methods easily. By default, when we create an object of the Collections class, it will be Both Readable and Writable. Read-
4 min read
Java Program that Shows Use of Collection Interface
The Collection framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details. Uses and advantages of Collection Framework: This reduces the efforts of programmers by providing data structures and algorithms, so we do not have to write them.This incre
3 min read
How to Insert all the Collection Elements to the Specified Position in Java ArrayList?
The element can be inserted at the collection elements to the specified position in ArrayList using Collection.addAll() method which is present in java.util.ArrayList class. If any element present at the index then that element and all its right side elements are shifted to the right side. this method accepts two arguments the first argument is the
3 min read
How to Remove an Element from Collection using Iterator Object in Java?
Collection in Java is a set of interfaces like List, Set, and Queue. An iterator in Java is used to iterate or traverse through the elements of the Collection. There are three types of iterator in Java namely, Enumerator, Iterator, and ListIterator. The two ways of removing an element from Collections using Iterator : Using IteratorUsing ListIterat
3 min read
Iterate Over Unmodifiable Collection in Java
The Collection is a framework that provides an architecture to store and manipulate the group of objects. In Java Collections, we perform operations like searching, sorting, Iterating over the given set of elements. Modifiable: Modifiable means we can perform operations like adding, deleting, updating elements in collection data structures. Example
3 min read
Java Program to Compare Elements in a Collection
A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit. Example: Input : List = [3, 5, 18, 4, 6] Output: Min value of our list : 3 max value of our list : 18 Input : List = ['a', 'a', 'a'] Output: All
2 min read
How to Iterate through Collection Objects in Java?
Any group of individual objects which are represented as a single unit is known as the Collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and interface in it. The Collection interface (java.util.Collection) and Map interface (java.util.Map) are
3 min read
Insert all Elements of Other Collection to Specified Index of Java ArrayList
ArrayList is part of the collection framework. It is a List and implements the java.util.list interface. ArrayList is a better alternative to Arrays, especially if you are not sure about the array size. Unlike array which has a fixed size, ArrayList can grow in size when needed. Internally ArrayList also uses arrays to store data. When it reaches t
2 min read
Java Program To Remove All The Duplicate Entries From The Collection
As we know that the HashSet contains only unique elements, ie no duplicate entries are allowed, and since our aim is to remove the duplicate entries from the collection, so for removing all the duplicate entries from the collection, we will use HashSet.The HashSet class implements the Set interface, backed by a hash table which is actually a HashMa
3 min read
Practice Tags :
three90RightbarBannerImg