Thursday, July 4, 2024
HomeLanguagesJavaAbstractSet toString() method in Java with Example

AbstractSet toString() method in Java with Example

The toString() method of Java AbstractSet is used to return a string representation of the elements of the Collection.

The String representation comprises a set representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used mainly to display collections other than String type(for instance: Object, Integer)in a String Representation.

Syntax:

public String toString()

Parameter The method does not take any parameters.

Return This method returns a String representation of the collection.

Below examples illustrate the toString() method:

Example 1:




// Java program to demonstrate
// Abstract Collection toString() method
  
import java.util.*;
  
public class collection {
    public static void main(String args[])
    {
        // Creating an Empty AbstractSet
        AbstractSet<String> abs
            = new TreeSet<String>();
  
        // Use add() method
        // to add elements to the Collection
        abs.add("Welcome");
        abs.add("To");
        abs.add("Geeks");
        abs.add("For");
        abs.add("Geeks");
  
        // Using toString() method
        System.out.println(abs.toString());
    }
}


Output:

[For, Geeks, To, Welcome]

Example 2:




// Java program to demonstrate
// Abstract Collection toString() method
  
import java.util.*;
  
public class collection {
    public static void main(String args[])
    {
        // Creating an Empty AbstractSet
        AbstractSet<Integer> abs
            = new TreeSet<Integer>();
  
        // Use add() method
        // to add elements to the Collection
        abs.add(10);
        abs.add(20);
        abs.add(30);
        abs.add(40);
  
        // Using toString() method
        System.out.println(abs.toString());
    }
}


Output:

[10, 20, 30, 40]

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments