×

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a string object.

Syntax

<String_Type> <string_variable> = "<sequence_of_string>";

Example

String str = "Hello!";

There are two methods for making String objects:

  1. String literal
  2. New keyword

1. String Literal: Java String literal is made by utilizing twofold statements.

For Example: String s = "Victory"; 

2. New Keyword: The new keyword is used for creating the String.

For Example: String s=new String("Victory");

Program in Java

public class StringExample{    
public static void main(String args[]){    
String v1="python";// making string by Java string literal
char ch[]={'v','i','c','t','o','r','y'};    
String v2=new String();//changing over char to string
String v3=new String("example");// making Java string by new keyword
System.out.println(v1);    
System.out.println(v2);    
System.out.println(v3);    
}
}    

Output

Reverse a String using Collections in Java

Collections in Java

The Collection in Java is a framework that gives a plan to store and control the get-together of things. Java Collections can accomplish each of the endeavours that you perform on a piece of information, for example, looking, sorting out, joining, controlling, and erasure.

Java Collection implies a solitary unit of items. Java Collection structure gives different affiliation centres (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet). The Collection interface (Java.util.Collection) and Map interface (Java.util.Map) are the two primaries "root" points of interaction of Java assortment classes.

To make a string object, you really want the Java.lang.String class. Java programming utilizes UTF - 16 to address a string. Strings are unchanging with the goal that their inside state stays steady after the article is totally made. The string object performs different tasks, yet turn-around strings in Java are the most generally utilized capability.

Framework

A framework is a bunch of classes and points of interaction which give an instant design. To carry out another element or a class, there is a compelling reason needed to characterize a structure. Notwithstanding, an ideal item situated plan generally incorporates a structure with an assortment of classes to such an extent that every one of the classes plays out a similar sort of errand.

Classes in Collection

There are various classes in the Collection. A couple of classes give full execution, while the rest give a skeletal plan. The different classes are examined underneath:

  • AbstractCollection: This class executes the greater part of the connection points which are characterized in the assortment.
  • AbstractList: This class acquires the AbstractCollection class and executes the majority of the connection points in the List Interface.
  • AbstractQueue: This class acquires the AbstractCollection class and carries out the greater part of the connection points in the Queue Interface.
  • AbstractSequentialList: This class acquires the AbstractList class for usage in records that employ sequential access. Sequential access occurs when each word is iterated individually.
  • LinkedList: This class acquires the AbstractSequentialList class and executes connected records.
  • ArrayList: This class acquires the AbstractList class and executes a unique exhibit. A unique exhibit is the one where the size is pronounced at run time.
  • ArrayDeque: This class acquires the AbstractCollection class and executes the dequeue interface. It executes a twofold finished line dynamic in nature.
  • AbstractSet: This class acquires the AbstractCollection class and executes the greater part of the connection points in the rundown interface.
  • EnumSet: This class extends the AbstractSet class and uses enum components.
  • HashSet: This class secures the AbstractSet class and uses it with the hash table.
  • LinkedHashSet: This class acquires the HashSet class and allows for cycles in the extension request.
  • PriorityQueue: This class obtains the AbstractQueue class and employs it in the creation of need lines.
  • TreeSet: This class obtained the AbstractSet class and used it to construct a coordinated set in the tree.

Collections.reverse() Method in Java

The reverse() strategy for Collections class as the actual name proposes is utilized for turning around components been there up in the article in which they are put away. It switches the request for components in a rundown passed as a contention.

The accompanying model exhibits how to utilize Collections. Reverse () to turn around Java's String. Following are the finished advances:

Make a vacant ArrayList of characters and introduce it with characters of the given String utilizing String.toCharArray().

Switch the rundown utilizing java.util.Collections turn around() technique.

At long last, convert the ArrayList into String utilizing StringBuilder and return the framed String.

Example: 1

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
 class Main
{
   
    public static String reverse(String str)
    {
          if (str == null || str.equals("")) {
            return str;
        }
 
           List<Character> list = new ArrayList<Character>();
         for (char c: str.toCharArray()) {
            list.add(c);
        }
 
               Collections.reverse(list);
        return list.stream().map(String::valueOf).collect(Collectors.joining());
    }
 
    public static void main(String[] args)
    {
        String str = "Reverse me!";
         str = reverse(str);
         System.out.println("The reversed string is " + str);
    }
}

Output

Reverse a String using Collections in Java

The above arrangement initial proselytes ArrayList into StringBuilder, then StringBuilder into a string. We can straightforwardly change over ArrayList into a string by eliminating square sections, commas, and single spaces from it. The accompanying code utilizes String.replaceAll() to accomplish that. Regardless, this approach is extraordinarily inefficient and should be avoided, come what may.

Example: 2

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
 
class Main
{
    // Method to reverse a string in Java using `Collections.reverse()`
    public static String reverse(String str)
    {
        if (str == null || str.equals("")) {
            return str;
        }
 
        List<Character> list = new ArrayList<Character>();
        for (char c: str.toCharArray()) {
            list.add(c);
        }
 
        
        Collections.reverse(list);
         return list.toString()
            .replaceAll("[,\\[\\]]", "")    // t h g i l e D   e i h c e T
            .replaceAll("  ", "@")          // t h g i l e D@ e i h c e T
            .replaceAll(" ", "")            // thgileD@eihceT
            .replaceAll("@", " ");          // !em esreveR
    }
 
    public static void main(String[] args)
    {
        String str = "Reverse me!";
         str = reverse(str);
         System.out.println("The reversed string is " + str);
    }

Output

Reverse a String using Collections in Java

That is tied in with switching a String utilizing the converse() strategy for Java Collections Framework.


Related Topics

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

Access Modifier in Java

The access modifiers in java are used to change the accessibility and scope of a method, constructor, class, and fields. If you are aware of C++ language, when we declare any member...

2 minutes read.

How to Call a Method in Java

In Java, a method is a collection of statements that perform a specific task or action.It can accept data with the help ofitsarguments. It  is also called a function. In order...

9 minutes read.

Calculator Program in Java

Calculator Program in Java A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case...

5 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Java String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.